You may encounter difficulty when attempting to create an std::function from a move-capturing lambda expression, despite having no issues creating the lambda itself. This is due to the restrictions imposed by the std::function constructor and its assignment operator.
The std::function constructor and operator= require that the argument be CopyConstructible. However, a move-capturing lambda that captures a move-only type (such as a std::unique_ptr) cannot be CopyConstructible.
To clarify, move-capturing refers to the capture mechanism employed by lambda expressions. In contrast to copy-capturing, which creates a copy of the captured variable, move-capturing transfers ownership of the variable to the lambda.
The code you provided illustrates the issue:
auto pi = std::make_unique<int>(0); auto foo = [q = std::move(pi)] { *q = 5; std::cout << *q << std::endl; }; std::function<void()> bar = foo; // Error: attempts to copy-construct 'foo'
The lambda expression 'foo' captures the unique pointer 'pi' by move, making it a move-only type. Therefore, constructing an std::function from 'foo' is not possible because 'foo' cannot be copied.
To circumvent this limitation, consider alternative approaches, such as using std::bind or creating a wrapper class that encapsulates the lambda and provides a CopyConstructible interface.
The above is the detailed content of Why Can't I Create an std::function from a Move-Capturing Lambda?. For more information, please follow other related articles on the PHP Chinese website!