gpt4 book ai didi

c++ - shared_ptr : Does the reference count increase when copying in a shared_ptr of the base class?

转载 作者:太空狗 更新时间:2023-10-29 23:15:21 25 4
gpt4 key购买 nike

documentation of boost::shared_ptr说:

shared_ptr<T> can be implicitly converted to shared_ptr<U> whenever T* can be implicitly converted to U*. In particular, shared_ptr<T> is implicitly convertible to shared_ptr<T const>, to shared_ptr<U> where U is an accessible base of T, and to shared_ptr<void>.

但我没有找到任何地方写的,如果这样做,它会增加引用计数器。

我试过下面的代码,it works :

struct A {
virtual int foo() {return 0;}
};

struct B : public A {
int foo() {return 1;}
};

int main() {
boost::shared_ptr<A> a;
{
boost::shared_ptr<B> b(new B());
a = b;
}

std::cout << a->foo() << std::endl; ///Prints 1
}

所以假设情况总是如此,但我找不到可以证实这一点的信息来源。

最佳答案

好的,当我写完问题时,我终于在 copy constructor documentation 中找到了答案。

shared_ptr(shared_ptr const & r); // never throws
template<class Y> shared_ptr(shared_ptr<Y> const & r); // never throws

Requires: Y* should be convertible to T*.

Effects: If r is empty, constructs an empty shared_ptr; otherwise, constructs a shared_ptr that shares ownership with r.

Postconditions: get() == r.get() && use_count() == r.use_count().

所以,答案是

关于c++ - shared_ptr : Does the reference count increase when copying in a shared_ptr of the base class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29701034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com