How to release pointer from boost::shared_ptr?

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

    I'm not entirely sure if your question is about achieving this, but if you want behaviour from a shared_ptr, where, if you release the value from one shared_ptr, all the other shared pointers to the same value become a nullptr, then you can put a unique_ptr in a shared_ptr to achieve that behaviour.

    void print(std::string name, std::shared_ptr>& ptr)
    {
        if(ptr == nullptr || *ptr == nullptr)
        {
            std::cout << name << " points to nullptr" << std::endl;
        }
        else
        {
            std::cout << name << " points to value " << *(*ptr) << std::endl;
        }
    }
    
    int main()
    {
        std::shared_ptr> original;
        original = std::make_shared>(std::make_unique(50));
    
        std::shared_ptr> shared_original = original;
    
        std::shared_ptr> thief = nullptr;
    
        print(std::string("original"), original);
        print(std::string("shared_original"), shared_original);
        print(std::string("thief"), thief);
    
        thief = std::make_shared>(original->release());
    
        print(std::string("original"), original);
        print(std::string("shared_original"), shared_original);
        print(std::string("thief"), thief);
    
        return 0;
    }
    

    Output:

    original points to value 50
    shared_original points to value 50
    thief points to nullptr
    original points to nullptr
    shared_original points to nullptr
    thief points to value 50
    

    This behaviour allows you to share a resource (like an array), then later reuse that resource while invalidating all the shared references to this resource.

提交回复
热议问题