快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

C++中如何使用lambda代替unique_ptr的Deleter-创新互联

这篇文章主要介绍C++中如何使用lambda代替unique_ptr的Deleter,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

创新互联建站是专业的韶关网站建设公司,韶关接单;提供成都网站建设、网站制作,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行韶关网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

代码

#include 
#include 
#include 
#include 
#include 
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 > a{ new go{}, d };//4
    //i.e. unique_ptr < go, function > 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”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联网站建设公司行业资讯频道!

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


当前文章:C++中如何使用lambda代替unique_ptr的Deleter-创新互联
转载来源:http://6mz.cn/article/ccopds.html

其他资讯