1

代码将被错误编译

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 时我的代码有什么问题?

4

1 回答 1

2

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

第二个版本之所以有效,是因为它不创建std::function对象,它fun是 lambda 的闭包类型(它是 lambda 表达式本身的类型)。

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

于 2019-01-04T07:54:13.990 回答