将lamda表达式复制到std :: function时出了什么问题

时间:2019-01-04 07:48:38

标签: c++ lambda c++14 unique-ptr std-function

代码将以eror编译

class A
{

};

int main()
{
    auto a = std::make_unique<A>();
    std::function<void()> fun = [ap = std::move(a)](){

    };
}

但是我用auto代替std :: function后就可以了

class A
{

};

int main()
{
    auto a = std::make_unique<A>();
    auto fun = [ap = std::move(a)](){

    };
}

错误是这样的:

C:/Qt/Qt5.11.1/Tools/mingw530_32/i686-w64-mingw32/include/c++/functional:1710:34: error: use of deleted function 'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'
    __dest._M_access<_Functor*>() =
                                  ^
C:\Users\Xiaopeng\CLionProjects\testGP\main.cpp:98:51: note: 'main()::<lambda()>::<lambda>(const main()::<lambda()>&)' is implicitly deleted because the default definition would be ill-formed:
     std::function<void()> fun = [ap = std::move(a)](){
                                                   ^
C:\Users\Xiaopeng\CLionProjects\testGP\main.cpp:98:51: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = A; _Dp = std::default_delete<A>]'
In file included from C:/Qt/Qt5.11.1/Tools/mingw530_32/i686-w64-mingw32/include/c++/memory:81:0,
                 from C:\Users\Xiaopeng\CLionProjects\testGP\main.cpp:3:
C:/Qt/Qt5.11.1/Tools/mingw530_32/i686-w64-mingw32/include/c++/bits/unique_ptr.h:356:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
   ^

用户std :: function时我的代码有什么问题?

1 个答案:

答案 0 :(得分:2)

std::function要求其中存储的可调用对象是可复制的。您的lambda无法复制,因为它包含只能移动的数据成员。

第二个版本起作用是因为它没有创建std::function对象,而是使fun成为lambda的闭包类型(这是lambda表达式本身的类型)。

如果需要将lambda存储在std::function中(例如,因为您需要将其存储在数据成员中),则必须以某种方式使其可复制。对于您而言,最简单的解决方案是使用std::shared_ptr而不是std::unique_ptr