c++ - 如何将删除器传递给 shared_ptr 持有的同一类中的方法

标签 c++ boost lambda shared-ptr raii

我有几个来自第 3 方库的类,类似于类 StagingConfigDatabase,它需要在创建后销毁。我正在为 RAII 使用 shared_ptr,但更愿意使用 单行代码 创建 shared_ptr,而不是像我的示例所示那样使用单独的模板仿函数。也许使用 lambda?还是绑定(bind)?

struct StagingConfigDatabase
{
  static StagingConfigDatabase* create();
  void destroy();
};

template<class T>
    struct RfaDestroyer
    {
        void operator()(T* t)
        {
            if(t) t->destroy();
        }
    };

    int main()
    {
      shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), RfaDestroyer<StagingConfigDatabase>());
    return 1;
    }

我在考虑这样的事情:

shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), [](StagingConfigDatabase* sdb) { sdb->destroy(); } );

但这并不能编译 :(

帮助!

最佳答案

我假设 createStagingConfigDatabase 中是静态的,因为没有它您的初始代码将无法编译。关于销毁,您可以使用简单的 std::mem_fun :

#include <memory>

boost::shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), std::mem_fun(&StagingConfigDatabase::destroy));

关于c++ - 如何将删除器传递给 shared_ptr 持有的同一类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4491610/

相关文章:

java - 用于引导 lambda 表达式或方法链接的方法引用的实用程序类?

c++ - 在 opengl 中使用 GLX_EXT_texture_from_pixmap 将窗口像素图绑定(bind)到纹理

c++ - GCC 相当于 MSVC 中的/GS、/GL、/Gy、/Oi、/MD

c++ - 访问 avl_set 中节点的左子节点或右子节点

c++ - booster::noncopyable 的用例是什么?

c# - 传递一个 Action 作为引用

c++ - AVR Library/Snippit 跟踪日期

c++ - 如何获取 SHORT 的高位和低位?

c++ - Boost sub_match 抛出 std::length_error 异常

java - 在java 8中从父级排序子级列表