Home > Backend Development > C++ > How Does `std::function` Achieve Versatile Callability with Consistent Size?

How Does `std::function` Achieve Versatile Callability with Consistent Size?

Susan Sarandon
Release: 2024-12-02 11:49:14
Original
556 people have browsed it

How Does `std::function` Achieve Versatile Callability with Consistent Size?

Implementing std::function for Versatile Callability

The std::function provides a way to encapsulate and store any type of callable while maintaining a fixed size. Despite the varying sizes of its contents, such as lambda expressions, std::function achieves this consistency through a technique known as type-erasure.

Type-Erasure for Diverse Callables

Type-erasure involves creating a common interface represented by a base class. In the case of std::function, a callable_base class defines a virtual function operator() that is implemented by derived classes for specific callable types. This approach enables std::function to store a pointer to the base class, allowing it to wrap any callable.

As each callable may have different implementations, the derived classes are created dynamically with std::function managing the allocation within the heap.

Copy Behavior and Internal State

When copying a std::function, the internal callable entity is copied, rather than shared. This behavior is evident in the following test:

int main() {
  int value = 5;
  typedef std::function<void()> fun;
  fun f1 = [=]() mutable { std::cout << value++ << '\n'; };
  fun f2 = f1;
  f1();                    // prints 5
  fun f3 = f1;
  f2();                    // prints 5
  f3();                    // prints 6 (copy after first increment)
}
Copy after login

The increment after the first call to f1 does not affect f2, which indicates that f2 has its own copy of the callable entity.

The above is the detailed content of How Does `std::function` Achieve Versatile Callability with Consistent Size?. 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