How to release pointer from boost::shared_ptr?

Don’t. Boost’s FAQ entry:

Q. Why doesn’t shared_ptr provide a release() function?

A. shared_ptr cannot give away ownership unless it’s unique() because the other copy will still destroy the object.

Consider:

shared_ptr<int> a(new int);
shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2

int * p = a.release();

// Who owns p now? b will still call delete on it in its destructor.

Furthermore, the pointer returned by release() would be difficult to deallocate reliably, as the source shared_ptr could have been created with a custom deleter.

So, this would be safe in case it’s the only shared_ptr instance pointing to your object (when unique() returns true) and the object doesn’t require a special deleter. I’d still question your design, if you used such a .release() function.

Leave a Comment