C++ 中使用lambda代替 unique_ptr 的Deleter的方法
代码 #include <iostream> #include <cstdlib> #include <memory> #include <string> #include <functional> using namespace std; class go { public: go() {} ~go() { cout << "go die.n"; } }; auto d = [] ( go * gp ) { delete gp; cout << "deletor done.n"; }; class go_de { public: void operator() ( go* g ) { d ( g ); } }; int main() { { unique_ptr < go,go_de > b{ new go{} };//1 } { //unique_ptr < go,decltype (d) > b{ new go{}}; complie error //2 unique_ptr < go,decltype (d) > a{ new go{},d };//3 } { unique_ptr < go,function<void(go*) > > a{ new go{},d };//4 //i.e. unique_ptr < go,[](go*gp) {delete gp;cout << "deletor done.n"; }}; } system ( "pause" ); return 0; } 描述 一般的,需要给一个模板的Concept参数时,都会像代码1的实现一样传入一个实现了该Concept的类型,例如go_de就实现了unique_ptr 的模板参数Deletor。 今天想尝试一下使用lambda表达式的类型作为模板参数传入,发现不行。原因在于 c++14 draft n4269 5.1.2 Lambda expressions 20 The closure type associated with a lambda-expression has no default constructor and a deleted copy assignment operator. It has a defaulted copy constructor and a defaulted move constructor (12.8). [ Note: These special member functions are implicitly defined as usual,and might therefore be defined as deleted. end note ] 意思就是 lambda 表达式没有默认的构造函数,operator=也被置为deleted。只有一个默认的复制构造函数和move构造函数。很显然,unique_ptr 的实现肯定是用到了Deletor Concept的默认构造函数的。所以编译不通过。这个在 2) Constructs a std::unique_ptr which owns p,initializing the stored pointer with p and value-initializing the stored deleter. Requires that Deleter is DefaultConstructible and that construction does not throw an exception.2) Constructs a std::unique_ptr which owns p,initializing the stored pointer with p and value-initializing the stored deleter. Requires that Deleter is DefaultConstructible and that construction does not throw an exception. 设想unique_ptr( pointer p,d1 );构造函数不存在,那Lambda类型就没法作为Concept传入了。 总结
毕竟,C++语言设计的原则是尽量不限制C++语言的用户的编程方式。 以上所述是小编给大家介绍的C++ 中使用lambda代替 unique_ptr 的Deleter的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |