How to release pointer from boost::shared_ptr?

后端 未结 14 1594
刺人心
刺人心 2020-11-30 06:42

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

14条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 07:14

    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 a(new int);
    shared_ptr 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.

提交回复
热议问题