这是演示问题的代码:
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
int main()
{
// lambda with a unique_ptr
auto u = std::make_unique<int>(10);
auto lambda = [u=std::move(u)]
{
cout << *u << endl;
};
// lambda itself is movable
auto lambdaM = std::move(lambda);
// lambda not able to move into a std::function - compiler trying to call the copy construtor, which is deleted
std::function<void(void)> func(std::move(lambda));
func();
}
该代码无法与以下代码一起编译:
g++-8 --std=c++2a -o move_lambda_to_function -g3 -rdynamic move_lambda_to_function.C
抱怨:
/usr/include/c++/8/bits/unique_ptr.h:394:7: note: declared here
unique_ptr(const unique_ptr&) = delete;
^~~~~~~~~~
似乎std :: function尝试复制而不是移动lambda对象,不知道为什么它不能与lambda一起使用时只有可移动对象?