我正在尝试移动已捕获了unique_ptr的lambda,但由于我不了解的原因而失败。据我了解,具有可移动成员的lambda表达式应该是可移动的。
我正在使用clang 3.8.1-24编译以下最小示例代码。
auto p = std::make_unique<int>(42);
auto l = [p{std::move(p)}]{};
std::vector<std::function<void()>> v;
v.push_back(std::move(l));
编译器抱怨push_back:
/usr/bin/../lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/functional:1571:10: error: call to implicitly-deleted copy constructor of '(lambda at test.cpp:8:11)'
new _Functor(*__source._M_access<_Functor*>());
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/functional:1606:8: note: in instantiation of member function 'std::_Function_base::_Base_manager<(lambda at test.cpp:8:11)>::_M_clone' requested here
_M_clone(__dest, __source, _Local_storage());
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/functional:2116:33: note: in instantiation of member function 'std::_Function_base::_Base_manager<(lambda at test.cpp:8:11)>::_M_manager' requested here
_M_manager = &_My_handler::_M_manager;
^
test.cpp:10:14: note: in instantiation of function template specialization 'std::function<void ()>::function<(lambda at test.cpp:8:11), void, void>' requested here
v.push_back(std::move(l));
^
test.cpp:8:12: note: copy constructor of '' is implicitly deleted because field '' has a deleted copy constructor
auto l = [p{std::move(p)}]{};
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/bits/unique_ptr.h:359:7: note: 'unique_ptr' has been explicitly marked deleted here
unique_ptr(const unique_ptr&) = delete;
^
删除移动捕获使代码得以编译。我将不胜感激,以了解为什么会发生这种错误,以及错误是在我这一边还是在标准库中。
任何变通方法也将非常有用,因为我需要将此lambda移入容器。