Search code examples
c++pointersdestructorshared-ptrfriend

How can I call a private destructor from a shared_ptr?


I have a resource_manager class which maintains a std::vector<boost::shared_ptr<resource> > internally. resource_manager is a friend class of resource. I want resources to only be created/deleted by resource_manager, so I made its constructors private (which works ok).

However, if I make the destructor private, the code doesn't compile because the destructor is called by boost::shared_ptr, which is not a friend of resource. I am thinking of enforcing the "do not delete by clients" rule by only returning only const resource* from the resource_manager, but somehow I am not satisfied with the security this method provides (what if a client somehow happens across a pointer to non-const?)

Apart from the obvious solution of not using shared_ptr, do you have any workaround / better solution to my problem?


Solution

  • 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);