Search code examples
c++boostshared-ptr

Sharing ownership of boost::shared_ptr after construction


Suppose I have two boost::shared_ptr's pointing to two different objects of class A:

boost::shared_ptr<A> x = boost::make_shared<A>();
boost::shared_ptr<A> y = boost::make_shared<A>();

At some point, I need x to discard ownership of the object it's owning and share ownership of the y's object with y. How can this be achieved (note that both shared_ptr's are constructed at that point, so no chance to use the copy constructor)?

Thanks!


Solution

  • You can simply assign it:

    x = y;
    

    See the assignment operators for std::shared_ptr and boost::shared_ptr assignment. You can verify this by checking the reference count before and after the assignment. This example uses C++11's std::shared_ptr but boost::shared_ptr would yield the same results:

    #include <memory>
    int main()
    {
        std::shared_ptr<int> x(new int);
        std::cout << x.use_count() << "\n"; // 1
        std::shared_ptr<int> y(new int);
        std::cout << x.use_count() << "\n"; // still 1
        y = x;
        std::cout << x.use_count() << "\n"; // 2
    }