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) }
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!