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, function<void(go*) > > a{ new go{}, [](go*gp) {delete gp;cout << "deletor done.\n"; }};
}
system ( "pause" );
return 0;
}
描述
一般的,需要給一個模板的Concept參數(shù)時,都會像代碼1的實現(xiàn)一樣傳入一個實現(xiàn)了該Concept的類型,例如go_de就實現(xiàn)了unique_ptr 的模板參數(shù)Deletor。
今天想嘗試一下使用lambda表達式的類型作為模板參數(shù)傳入,發(fā)現(xiàn)不行。原因在于
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 表達式?jīng)]有默認的構造函數(shù),operator=也被置為deleted。只有一個默認的復制構造函數(shù)和move構造函數(shù)。很顯然,unique_ptr 的實現(xiàn)肯定是用到了Deletor Concept的默認構造函數(shù)的。所以編譯不通過。這個在
unique_ptr構造函數(shù)頁寫的很清楚。
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 );構造函數(shù)不存在,那Lambda類型就沒法作為Concept傳入了。
總結
- 想用Lambda表達式的類型作為Concept,使用類型推導關鍵字decltype
- Lambda的類型沒有default constructor、copy assignment operator.
- 寫C++庫的時候,如果用到模板和Concept技術,要考慮添加Concept對象做參數(shù)的類型的構造函數(shù)從而才能不限制Lambda表達式類型作為Concept傳入。
畢竟,C++語言設計的原則是盡量不限制C++語言的用戶的編程方式。
以上所述是小編給大家介紹的C++ 中使用lambda代替 unique_ptr 的Deleter的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
C++類靜態(tài)成員與類靜態(tài)成員函數(shù)詳解
靜態(tài)成員不可在類體內(nèi)進行賦值,因為它是被所有該類的對象所共享的。你在一個對象里給它賦值,其他對象里的該成員也會發(fā)生變化。為了避免混亂,所以不可在類體內(nèi)進行賦值2013-09-09
C語言將數(shù)組中元素的數(shù)排序輸出的相關問題解決
這篇文章主要介紹了C語言將數(shù)組中元素的數(shù)排序輸出的相關問題解決,文中的題目是將元素連接起來排成一個數(shù)并要求出這類結果中數(shù)最小的一個,需要的朋友可以參考下2016-03-03

