I have a lambda which moved a unique pointer into itself:
auto my_ptr = std::make_unique<int>(3);
auto my_lambda = [my_ptr = std::move(my_ptr)]() mutable {
// ...
};
I want to move that lambda into std::function:
std::function<void()> func = std::move(my_lambda);
But I get the error that std::function target must be copy-constructible.
Of course if I try to use auto instead of std::function it works, but it doesn’t work for my case. I have a struct which contains std::function and you cant use auto in a struct.
If there any way of moving the lambda into that function pointer?
>Solution :
Nope, this is unfortunately std::function‘s absolute requirement: it requires a copy-constructible callable object. The precludes using any callable object that captures a move-only object.
This is why C++23 introduced std::move_only_function.