捕获并移动 c++14 lambda 表达式中的unique_ptr
Capture and move a unique_ptr in a c++14 lambda expression
我以这种方式在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);
};
auto lambda = [ capturedStr = std::move(str) ] {
cout << *capturedStr.get() << endl;
auto str2 = std::move(capturedStr); // <--- Not working, why?
};
为了提供更多详细信息,编译器正在有效地进行此转换:
class NameUpToCompiler
{
unique_ptr<string> capturedStr; // initialized from move assignment in lambda capture expression
void operator()() const
{
cout << *capturedStr.get() << endl;
auto str2 = std::move(capturedStr); // move will alter member 'captureStr' but can't because of const member function.
}
}
在 lambda 上使用 mutable
将从 operator()
成员函数中删除const
,从而允许更改成员。
为了使建议更明确:添加mutable
:http://coliru.stacked-crooked.com/a/a19897451b82cbbb
#include <memory>
int main()
{
std::unique_ptr<int> pi(new int(42));
auto ll = [ capturedInt = std::move(pi) ] () mutable { };
}
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误