Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ move a lambda to std::function which contains unique_ptr

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading