Home > Backend Development > C++ > Why Can't I Create an std::function from a Move-Capturing Lambda?

Why Can't I Create an std::function from a Move-Capturing Lambda?

Susan Sarandon
Release: 2024-12-13 10:10:11
Original
114 people have browsed it

Why Can't I Create an std::function from a Move-Capturing Lambda?

Constructing an std::function from a Move-Capturing Lambda

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'
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template