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!
You can simply assign it:
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_ptrbutboost::shared_ptrwould yield the same results: