I need to move a unique_ptr
to a std::function
closure. I'm using generalized lambda captures in C++14.
auto ptr = make_unique<Foo>();
// Works.
auto lambda = [p = move(ptr)] { };
// This does not compile.
std::function<void()> func = [p = move(ptr)] { };
It's trying to copy, rather than move, the lambda capture into the std::function
. The relevant error is:
copy constructor of '' is implicitly deleted because field '' has a deleted copy
constructor
std::function<void()> func = [p = move(ptr)] { };
The example here would make this seem to work.
Note that the answer here just repeats the example on isocpp.org.
I can move to a shared_ptr
as follows:
shared_ptr<Foo> s = move(ptr);
but that creates another issue, because I need to call a function that expects a unique_ptr
from within my lambda, and I can't convert a shared_ptr
back to a unique_ptr
.
Is it possible to capture a unique_ptr
in a std::function
?