How can I call a private destructor from a shared_

2019-02-09 16:15发布

问题:

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?

回答1:

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


回答2:

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."