本文介绍了如何从shared_ptr调用私有析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 resource_manager 类,它维护一个 std :: vector< boost :: shared_ptr< resource> > resource_manager resource 的朋友类。我希望 resource 只能通过 resource_manager 创建/删除,所以我把它的构造函数私有。

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

但是,如果我使析构函数私有,代码不会编译,因为析构函数被调用 boost :: shared_ptr ,这不是 resource 的朋友。我想从 resource_manager 中只返回 const resource * ,强制执行 ,但不知何故我不满意这种方法提供的安全性(如果一个客户端发生在一个指向非const的指针)。

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

除了明显的解决方案没有使用 shared_ptr ,您有任何解决方法/更好的解决我的问题吗?

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

推荐答案

您可以将自定义删除程序传递给共享指针。所以只需创建一个删除函子或函数(由你决定),然后依次是你的类的朋友

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

这篇关于如何从shared_ptr调用私有析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 04:01