c++ - 在 c++14 lambda 表达式中捕获和移动 unique_ptr

标签 c++ c++11 lambda c++14

我以这种方式在 lambda 表达式中捕获 unique_ptr:

auto str = make_unique<string>("my string");
auto lambda = [ capturedStr = std::move(str) ] {
   cout << *capturedStr.get() << endl;
};
lambda();

在我尝试将 capturedStr 移动到另一个 unique_ptr 之前,它工作得很好。例如,以下内容不起作用:

auto str = make_unique<string>("my string");
auto lambda = [ capturedStr = std::move(str) ] {
    cout << *capturedStr.get() << endl;
    auto str2 = std::move(capturedStr); // <--- Not working, why?
};
lambda();

这是编译器的输出:

.../test/main.cpp:11:14: error: call to implicitly-deleted copy
constructor of 'std::__1::unique_ptr<std::__1::basic_string<char>,
std::__1::default_delete<std::__1::basic_string<char> > >'
        auto str2 = std::move(capturedStr);
             ^      ~~~~~~~~~~~~~~~~~~~~~~ ../include/c++/v1/memory:2510:31: note: copy constructor is implicitly
deleted because 'unique_ptr<std::__1::basic_string<char>,
std::__1::default_delete<std::__1::basic_string<char> > >' has a
user-declared move constructor
    _LIBCPP_INLINE_VISIBILITY unique_ptr(unique_ptr&& __u) _NOEXCEPT
                              ^ 1 error generated.

为什么不能移动capturedStr

最佳答案

lambda 的 operator () 默认为 const,不能从 const 对象中移动。

如果要修改捕获的变量,请声明它mutable

auto lambda = [ capturedStr = std::move(str) ] () mutable {
//                                             ^^^^^^^^^^
    cout << *capturedStr.get() << endl;
    auto str2 = std::move(capturedStr);
};

关于c++ - 在 c++14 lambda 表达式中捕获和移动 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27800468/

相关文章:

c++ - 为什么我的控制台窗口在我的程序完成之前就关闭了?

c++ - undefined reference std::pair

lambda - DrRacket : lambda anonymous function

Java 8 流 "ifPresent"

c++ - 为什么auto_ptr中有模板复制构造函数和重写操作函数?

c++ - 有什么方法可以捕获在构造静态/全局时抛出的异常?

c++ - 当 size_t 类型的变量 t 被赋予负值时,它的实际值是多少?(可以是 unsigned int 而不是 size_t)

c++ - 初学者 C++ - try catch 异常

c++ - 使用 Cygwin boost asio 错误

c# - Entity Framework 日期组合查询