How can I call a private destructor from a shared_ptr?

醉酒当歌 提交于 2019-11-30 09:30:01

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!