• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++用lambda代替unique_ptr的Deleter

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

代码

#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构造函数页写的很清楚。

  1. 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++语言的用户的编程方式

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c++之拷贝构造函数调用时机发布时间:2022-07-13
下一篇:
java—c3p0utils封装发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap