![](/img/trans.png)
[英]How to return a std::function that contains a std::unique_ptr from a generalized lambda capture in C++14?
[英]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 { };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.