我這樣捕獲的unique_ptr在lambda表達式移動的unique_ptr:捕獲和在C++ 14 lambda表達式
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
?
Lambdas'operator()'是'const',除非它被聲明爲'mutable',並且你不能從'const'對象移動。 –
謝謝@ T.C。,你能寫一個答案,我會接受它 – MartinMoizard