How to release pointer from boost::shared_ptr?

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

    Forgive them for they know not what they do. This example works with boost::shared_ptr and msvs std::shared_ptr without memory leaks!

    template <template <typename> class TSharedPtr, typename Type>
    Type * release_shared(TSharedPtr<Type> & ptr)
    {
        //! this struct mimics the data of std:shared_ptr ( or boost::shared_ptr )
        struct SharedVoidPtr
        {
            struct RefCounter
            {
                long _Uses;
                long _Weaks;
            };
    
            void * ptr;
            RefCounter * refC;
    
            SharedVoidPtr()
            {
                ptr = refC = nullptr;
            }
    
            ~SharedVoidPtr()
            {
                delete refC;
            }
        };
    
        assert( ptr.unique() );
    
        Type * t = ptr.get();
    
        SharedVoidPtr sp; // create dummy shared_ptr
        TSharedPtr<Type> * spPtr = (TSharedPtr<Type>*)( &sp );
        spPtr->swap(ptr); // swap the contents
    
        ptr.reset();
        // now the xxx::shared_ptr is empy and
        // SharedVoidPtr releases the raw poiter but deletes the underlying counter data
        return t;
    }
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
提交回复
热议问题