如何将删除器传递给由shared_ptr持有的同一类中的方法
我有几个来自第三方库的类,类似于 StagingConfigDatabase 类,它需要在创建后销毁。我正在为 RAII 使用shared_ptr,但更愿意使用单行代码创建shared_ptr,而不是像我的示例所示使用单独的模板函子。也许使用 lambda 表达式?或绑定?
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(); } );
但这不能编译:(
救命!
I have several classes from 3rd party library similar to the class, StagingConfigDatabase, which requires to be destroyed after it is created. I am using a shared_ptr for RAII but would prefer to create the shared_ptr using a single line of code rather than using a seperate template functor as my example shows. Perhaps using lambdas? or 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;
}
I was considering something like:
shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), [](StagingConfigDatabase* sdb) { sdb->destroy(); } );
but that doesn't compile :(
Help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设
create
在StagingConfigDatabase
中是静态的,因为如果没有它,您的初始代码将无法编译。关于销毁,您可以使用简单的std::mem_fun
< /a>:I'll assume that
create
is static inStagingConfigDatabase
because your initial code wouldn't compile without it. Regarding destruction, you can use a simplestd::mem_fun
:你使用什么编译器?它是否支持 lambda 等 C++0x 功能?以下内容(与您的示例基本相同)在 MSVC 2010 下编译并工作正常:
“工作正常”,我的意思是“输出 X::create 后跟 X::destroy”。
What compiler are you using? Does it support C++0x features like lambdas? The following (which is basically the same as your example) compiles and works fine for me under MSVC 2010:
By "works fine", I mean "outputs X::create followed by X::destroy".