What kind of magic does the std::function
from C++11 that its sizeof = 32
? If I\'d store the function reference as a pointer, it\
std::function
is indeed magic, as it can be constructed from any callable object! It will happily store any amount of state for you, even if on the surface you retain a measly void(int&)
signature.
There's certainly a price attached to this magic, which typically uses some sort of type erasure (i.e. a dynamic allocation and virtual dispatch) internally. The details vary, but the resulting objects are certainly "heavy" — which is why they should be avoided in favour of auto
and templates whenever feasible!
For std::function<Signature>
it is a trade-off between object size and allocation which is interesting: For small function objects it is desirable to avoid an allocation. On the other hand, doing so increases the object size. For the small function optimization to be useful and not introduce overheads when actually calling the object, the object size needs to be at least two pointers plus some memory to store simple function objects. It seems that a size of 32 bytes is exactly this (on a system where sizeof(T*)
is 8).
That is, internally a std::function<Signature>
object stores an inheritance hierarchy: The base class provides the interface to be called, delegating to a templatized derived which implements the call interface (plus, probably, some clone()
functionality). In an implementation optimized for size the function object would just keep a pointer to the base, but to avoid allocation it would set aside some internal storage to allocate the entire object in and point to this object (the internal pointer avoids a condition when actually calling the function object). The memory needed for the object is a virtual function pointer plus any data for the actual function object the std::function<Signature>
object is initialized with. To accommodate member functions with their object it seems that two more words is reasonably small.