Can boost::shared_ptr release the stored pointer without deleting it?
I can see no release function exists in the documentation, also in the FAQ is explained why it
I needed to pass a pointer through async handlers and to keep the self-destruct behavior in case of failure but the final API expected a raw pointer, so I made this function to release from a single shared_ptr:
#include
template
T * release(std::shared_ptr & ptr)
{
struct { void operator()(T *) {} } NoDelete;
T * t = nullptr;
if (ptr.use_count() == 1)
{
t = ptr.get();
ptr.template reset(nullptr, NoDelete);
}
return t;
}
If ptr.use_count() != 1
you shall get a nullptr
instead.
Do note that, from cppreference (bold emphasis mine):
If
use_count
returns 1, there are no other owners. (The deprecated member functionunique()
is provided for this use case.) In multithreaded environment, this does not imply that the object is safe to modify because accesses to the managed object by former shared owners may not have completed, and because new shared owners may be introduced concurrently, such as bystd::weak_ptr::lock
.