How to release pointer from boost::shared_ptr?

后端 未结 14 1608
刺人心
刺人心 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:10

    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 function unique() 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 by std::weak_ptr::lock.

提交回复
热议问题