c – 如何将删除器传递给shared_ptr所在的同一个类中的方法
发布时间:2020-12-16 09:31:24 所属栏目:百科 来源:网络整理
导读:我有来自第三方库的几个类,类似于StagingConfig Database类,它需要在创建后销毁.我正在为RAII使用shared_ptr,但更喜欢使用单行代码创建shared_ptr,而不是像我的示例所示使用单独的模板仿函数.也许使用lambdas?还是绑定? struct StagingConfigDatabase{ sta
我有来自第三方库的几个类,类似于StagingConfig
Database类,它需要在创建后销毁.我正在为RAII使用shared_ptr,但更喜欢使用单行代码创建shared_ptr,而不是像我的示例所示使用单独的模板仿函数.也许使用lambdas?还是绑定?
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(); } ); 但那不编译:( 救命! 解决方法
我假设在StagingConfigDatabase中create是静态的,因为如果没有它,你的初始代码将无法编译.关于破坏,你可以使用一个简单的
std::mem_fun :
#include <memory> boost::shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(),std::mem_fun(&StagingConfigDatabase::destroy)); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |