我有几个来自第 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(); } );
但这并不能编译 :(
帮助!
最佳答案
我假设 create
在 StagingConfigDatabase
中是静态的,因为没有它您的初始代码将无法编译。关于销毁,您可以使用简单的 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/