作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我只是想使用 shared_ptr 的删除器功能而不使用 shared_ptr 部分。比如,当 shared_ptr 超出范围并且删除器不需要传递给它的任何指针时,我想调用一个函数。
我有这个,但是很俗气。
shared_ptr<int> x(new int, [&](int *me) { delete me; CloseResource(); });
有没有办法不将任何指针与 shared_ptr 相关联?
更新:根据许多建议,unique_ptr 方式如下所示:
unique_ptr<int, std::function<void(int*)>> x(new int, [&](int *me) {delete me; CloseResource();});
坦率地说,这看起来比 shared_ptr 版本更糟糕,但实际上“更好”。
更新:对于那些喜欢使用这个简单的范围关闭函数调用者的人,我让它变得更简单了,你甚至不需要分配或释放一个对象:
shared_ptr<int> x(NULL, [&](int *) { CloseResource(); });
最佳答案
听起来您可能试图做的是将“删除”责任移交给“其他人”,这样您就不必再担心了。如果是这样的话,unique_ptr
(不是 shared_ptr
)与自定义删除器一起工作:
struct Foo final {};
Foo* New() { return new Foo; }
void Delete(Foo* p) { delete p; }
int main()
{
auto p = New();
std::unique_ptr<Foo, decltype(&Delete)> up(p, &Delete);
}
列出了很多类似的解决方案here ;如果没有关于您的实际 API 的更多信息(例如,HANDLE
is really a pointer 技巧是否有效?),就没有什么可以做的了。更多阅读 The simplest and neatest c++11 ScopeGuard ,包括 link到建议的 std::unique_resource
。
关于c++ - 如何仅将 shared_ptr 用于删除器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42397947/
我是一名优秀的程序员,十分优秀!