unique_ptr第二个参数,不能用内联lambda声明

C++语言 码拜 9年前 (2015-11-02) 1007次浏览
本人有3个unique_ptr的声明,都使用了第二个模板类型参数来指明,到底要用什么样子的deleter:
[code=c]
auto df = [](string*p) {delete p; };
auto sp = unique_ptr < string, decltype(df) > (new string); //OK
auto sp1 = unique_ptr < string, decltype([](string*p) {delete p; }) >(new string); //编译错误
auto sp2 = unique_ptr < string, default_delete<string>>(new string);//OK
[code]
本人用gcc4.7和vc2015都抱相似的错误:
gcc报错: lambda-expression in unevaluated context
VC报错:a lambda is not allowed in an unevaluated expression
奇怪,先声明一个lambda,然后再decltype是可以的,但是想不要单独给lambda弄一个变量,直接放到unique_ptr的那句声明里面去,可以吗?
C++11/14里面可以做到吗?
解决方案:10分
很遗憾, 本人的vs2015连.

    auto tdeleter = [](int* p) { std::free(p); };
    std::unique_ptr<int, decltype(tdeleter)> ptr(reinterpret_cast<int*>(std::malloc(100)));

都不行, 必须初始化:

    auto tdeleter = [](int* p) { std::free(p); };
    std::unique_ptr<int, decltype(tdeleter)> ptr(reinterpret_cast<int*>(std::malloc(100)), tdeleter);
解决方案:10分
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 ]

std::unique_ptr<int, decltype(tdeleter)> ptr(reinterpret_cast<int*>(std::malloc(100)));
需要使用默认构造函数重新构造一个 decltype(tdeleter) 类型的变量。
解决方案:10分
std::unique_ptr<char, decltype(&free)> p((char *)malloc(100), free);

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明unique_ptr第二个参数,不能用内联lambda声明
喜欢 (0)
[1034331897@qq.com]
分享 (0)