8

Are captured arguments copied during the conversion of lambdas to std::function?
I need to convert a lambda that captures a non-copyable type to std::function.
So I passed a lambda to std::function as an rvalue, but an error occurred.

// Foo is non-copyable.
auto a = [f = Foo()]{ };
std::function<void()> b = std::move(a) // error, calls deleted Foo::Foo(const Foo&);
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 2
    Possible duplicate: [How to create an std::function from a move-capturing lambda expression?](https://stackoverflow.com/questions/25421346/how-to-create-an-stdfunction-from-a-move-capturing-lambda-expression) – cpplearner Dec 27 '19 at 03:51

1 Answers1

5

Yes, std::function requires the function object to be CopyConstructible and can't be used with move-only function objects.

Type requirements

You can wrap the lambda into std::reference_wrapper like std::function<void()> b = std::ref(a);, but then you have to be careful of the lifetime of the lambda object. Or you may try to stop using std::function and use lambda directly; especially in template context.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • First of all thank you for the answers. But I could not find one of your answers that could solve my problem. Because what I want to make is to bind an argument to a function and store that function in a queue. Is there any other way to solve my problem? –  Dec 27 '19 at 02:15
  • 1
    @blAs1N: You would have to write something like `std::function`, but which only requires moveability. That's too big of a task for a Stack Overflow Q&A. – Nicol Bolas Dec 27 '19 at 02:19
  • 1
    Another solution is to write a callable wrapper for `shared_ptr`. – Brian Bi Dec 27 '19 at 02:19
  • @NicolBolas Maybe it's not _that_ big a task? https://stackoverflow.com/questions/25330716/move-only-version-of-stdfunction . – cpplearner Dec 27 '19 at 03:57