国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++ 中使用lambda代替 unique_ptr 的Deleter的方法

2020-01-26 14:11:24
字體:
來源:轉載
供稿:網友

代碼

#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參數時,都會像代碼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的默認構造函數的。所以編譯不通過。這個在
unique_ptr構造函數頁寫的很清楚。

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傳入了。

總結

  • 想用Lambda表達式的類型作為Concept,使用類型推導關鍵字decltype
  • Lambda的類型沒有default constructor、copy assignment operator.
  • 寫C++庫的時候,如果用到模板和Concept技術,要考慮添加Concept對象做參數的類型的構造函數從而才能不限制Lambda表達式類型作為Concept傳入。

畢竟,C++語言設計的原則是盡量不限制C++語言的用戶的編程方式。

以上所述是小編給大家介紹的C++ 中使用lambda代替 unique_ptr 的Deleter的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乡城县| 宁城县| 滨海县| 密云县| 星子县| 乌恰县| 沧源| 钟祥市| 佛坪县| 伊通| 曲沃县| 民县| 桂林市| 虹口区| 罗源县| 南召县| 珲春市| 自贡市| 湘潭市| 温泉县| 大悟县| 广德县| 新闻| 鄱阳县| 湟中县| 屯昌县| 乌鲁木齐市| 日土县| 从江县| 视频| 淮滨县| 益阳市| 河北区| 扎囊县| 余姚市| 宽甸| 宁都县| 永福县| 阿合奇县| 黔东| 福建省|