Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to release pointer from boost::shared_ptr?

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 does not provide release function, something like that the release can not be done on pointers that are not unique. My pointers are unique. How can I release my pointers ? Or which boost smart pointer class to use that will allow me releasing of the pointer ? I hope that you won't say use auto_ptr :)

like image 638
user152508 Avatar asked Oct 06 '09 13:10

user152508


2 Answers

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.

like image 189
sellibitze Avatar answered Sep 25 '22 13:09

sellibitze


You could use fake deleter. Then pointers will not be deleted actually.

struct NullDeleter {template<typename T> void operator()(T*) {} };  // pp of type some_t defined somewhere boost::shared_ptr<some_t> x(pp, NullDeleter() ); 
like image 29
Kirill V. Lyadvinsky Avatar answered Sep 23 '22 13:09

Kirill V. Lyadvinsky