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 to shared_ptr<U>

whenever T*

can be implicitly converted to U *. In particular, it is shared_ptr<T>

implicitly convertible to shared_ptr<T const>

, to shared_ptr<U>

, where U

is the available base T

and shared_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.

+3


source to share


1 answer


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 .

0


source







All Articles