C++ 中使用lambda代替 unique_ptr 的Deleter的方法
代码
#include#include #include #include #include usingnamespacestd; classgo { public: go(){} ~go() { cout<<"godie.\n"; } }; autod=[](go*gp) { deletegp; cout<<"deletordone.\n"; }; classgo_de { public: voidoperator()(go*g) { d(g); } }; intmain() { { unique_ptr b{newgo{}};//1 } { //unique_ptr b{newgo{}};complieerror//2 unique_ptr a{newgo{},d};//3 } { unique_ptr >a{newgo{},d};//4 //i.e.unique_ptr >a{newgo{},[](go*gp){deletegp;cout<<"deletordone.\n";}}; } system("pause"); return0; }
描述
一般的,需要给一个模板的Concept参数时,都会像代码1的实现一样传入一个实现了该Concept的类型,例如go_de就实现了unique_ptr的模板参数Deletor。
今天想尝试一下使用lambda表达式的类型作为模板参数传入,发现不行。原因在于
c++14draftn4269
5.1.2Lambdaexpressions
20Theclosuretypeassociatedwithalambda-expressionhasnodefaultconstructorandadeletedcopyassignmentoperator.Ithasadefaultedcopyconstructorandadefaultedmoveconstructor(12.8).[Note:Thesespecialmemberfunctionsareimplicitlydefinedasusual,andmightthereforebedefinedasdeleted.endnote]
意思就是lambda表达式没有默认的构造函数,operator=也被置为deleted。只有一个默认的复制构造函数和move构造函数。很显然,unique_ptr的实现肯定是用到了DeletorConcept的默认构造函数的。所以编译不通过。这个在
unique_ptr构造函数页写的很清楚。
2)Constructsastd::unique_ptrwhichownsp,initializingthestoredpointerwithpandvalue-initializingthestoreddeleter.RequiresthatDeleterisDefaultConstructibleandthatconstructiondoesnotthrowanexception.2)Constructsastd::unique_ptrwhichownsp,initializingthestoredpointerwithpandvalue-initializingthestoreddeleter.RequiresthatDeleterisDefaultConstructibleandthatconstructiondoesnotthrowanexception.
设想unique_ptr(pointerp,d1);构造函数不存在,那Lambda类型就没法作为Concept传入了。
总结
- 想用Lambda表达式的类型作为Concept,使用类型推导关键字decltype
- Lambda的类型没有defaultconstructor、copyassignmentoperator.
- 写C++库的时候,如果用到模板和Concept技术,要考虑添加Concept对象做参数的类型的构造函数从而才能不限制Lambda表达式类型作为Concept传入。
毕竟,C++语言设计的原则是尽量不限制C++语言的用户的编程方式。
以上所述是小编给大家介绍的C++中使用lambda代替unique_ptr的Deleter的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!