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

Can I Create an `std::function` from a Move-Capturing Lambda Expression?

Barbara Streisand
Release: 2024-12-11 13:46:11
Original
1011 people have browsed it

Can I Create an `std::function` from a Move-Capturing Lambda Expression?

Creating an std::function from a Move-Capturing Lambda Expression

It is possible to construct an std::function from a move-capturing lambda expression; however, certain restrictions apply.

Template Constructor

An std::function can be constructed from a move-capturing lambda using the following template constructor:

template<class F>
function(F f);
Copy after login

Requirements

For this constructor to work, the following requirements must be met:

  • The lambda expression's capture must be copy-constructible.
  • The lambda expression must be Callable with the specified argument types and return type.
  • The lambda's capture's copy constructor and destructor must not throw exceptions.

Move-Only Types

It is not possible to construct an std::function from a lambda that move-captures a move-only type. This is because std::function's copy constructor and assignment operator are defined in terms of a constructor that requires copy-constructible types.

Example

Consider the following code snippet:

auto pi = std::make_unique<int>(0);

// Move-capturing lambda
auto foo = [q = std::move(pi)] {
    *q = 5;
    std::cout << *q << std::endl;
};
Copy after login

Attempting to create an std::function from this lambda using any of the following approaches will result in a compilation error:

std::function<void()> bar = foo;
std::function<void()> bar{foo};
std::function<void()> bar{std::move(foo)};
std::function<void()> bar = std::move(foo);
std::function<void()> bar{std::forward<std::function<void()>>(foo)};
std::function<void()> bar = std::forward<std::function<void()>>(foo);
Copy after login

This is because pi is a move-only type, and std::function's copy constructor requires copy-constructible types.

Therefore, if you wish to use a move-capturing lambda with std::function, ensure that its capture is copy-constructible.

The above is the detailed content of Can I Create an `std::function` from a Move-Capturing Lambda Expression?. 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