Here is the code to demo the problem:
#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();
}
The code doesn't compile with:
g++-8 --std=c++2a -o move_lambda_to_function -g3 -rdynamic move_lambda_to_function.C
complaining about:
/usr/include/c++/8/bits/unique_ptr.h:394:7: note: declared here
unique_ptr(const unique_ptr&) = delete;
^~~~~~~~~~
It seems like std::function try to copy, rather than move the lambda object, any idea why it is not working with lambda has movable-only object?