#include <functional>
#include <memory>
#include <string>
#include <iostream>
void foo(std::function<void()> f)
{
f();
}
int main()
{
std::unique_ptr<int> handle = std::make_unique<int>(5);
foo(
[h = std::move(handle)]() mutable
{
std::cout << *h << std::endl;
});
}
Following code doen't compile with error
C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.28.29910\include\functional(914,58): error C2280: 'main::<lambda_1aa523ba59bbecea5306bc1fd178120f>::<lambda_1aa523ba59bbecea5306bc1fd178120f>(const main::<lambda_1aa523ba59bbecea5306bc1fd178120f> &)': attempting to reference a deleted function
The std::function
requires the function object to be Copy-Constructible, so you can't expect a lamdba to be moved to it. On initialization, it attempts to copy the lambda and so the std::unique_ptr
with it, which is a member of this lambda, and, expectedly, fails to do so. What you can do is store your lambda in a variable and pass it to function that accepts const std::function&
using std::ref
like that:
void foo(const std::function<void()>& f); // function declaration
auto a = [h = std::move(handle)]() mutable
{
std::cout << *h << std::endl;
};
foo(std::ref(a));
This is a related question with much more detailed answers: How to create an std::function from a move-capturing lambda expression?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With