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\
For std::function
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
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
object is initialized with. To accommodate member functions with their object it seems that two more words is reasonably small.