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&);
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
@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.
Another solution is to write a callable wrapper for shared_ptr<Foo>.
@NicolBolas Maybe it's not that big a task? stackoverflow.com/questions/25330716/… .