Shared_ptr: does the reference count increase when copied to a shared_ptr of the base class?
boost :: shared_ptr documentation says:
shared_ptr<T>
can be implicitly converted toshared_ptr<U>
wheneverT*
can be implicitly converted to U *. In particular, it isshared_ptr<T>
implicitly convertible toshared_ptr<T const>
, toshared_ptr<U>
, whereU
is the available baseT
andshared_ptr<void>
.
But I haven't found anything if doing so will increase the reference count.
I tried the following code and 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
}
So, suppose this is always the case, but I could not find a source of information that would confirm this.
source to share
Ok, when I finished writing the question, I finally found the answer in the instance constructor documentation
shared_ptr(shared_ptr const & r); // never throws template<class Y> shared_ptr(shared_ptr<Y> const & r); // never throws
Required: Y * must be convertible to T *.
Effects: if r is empty, an empty shared_ptr is created; otherwise creates a shared_ptr that owns r .
Postconditions:
get() == r.get()
&& .use_count() == r.use_count()
So the answer is YES .
source to share