How can I call a private destructor from a shared_ptr?

后端 未结 2 1946
清歌不尽
清歌不尽 2020-12-30 11:39

I have a resource_manager class which maintains a std::vector > internally. resource_manager i

相关标签:
2条回答
  • 2020-12-30 12:03

    Perhaps declare shared_ptr<resource> as a friend? shared_ptr doesn't call the constructor, and should only destruct if your resource manager releases the pointer before all clients have destroyed their shared_ptrs. This won't allow clients to break the protection, but will allow clients to keep a resource alive against the resource_manager's "will."

    0 讨论(0)
  • 2020-12-30 12:09

    You can pass a custom deleter to the shared pointer. So just create a deleter functor or function (up to you) which in turn is a friend of your class:

    class Secret
    {
      ~Secret() { }
      friend class SecretDeleter;
      friend void SecretDelFunc(Secret *);
    };
    
    class SecretDeleter
    {
    public:
      void operator()(Secret * p) { delete p; }
    };
    
    void SecretDelFunc(Secret * p) { delete p; }
    
    std::shared_ptr<Secret> sp1(new Secret, SecretDeleter());
    std::shared_ptr<Secret> sp2(new Secret, SecretDelFunc);
    
    0 讨论(0)
提交回复
热议问题