for a std::function how can one easily determine if the captures requre allocation (or not)

89 Views Asked by At

An instance of std::function has space in itself for containing a limited size of "captured" arguments. to avoid thrashing memory allocations I want to make sure some of the instances of std::function I use do not require an extra allocation for the arguments.

For a specific platform/header is there an easy way to determine what the max size of captures is before it makes a secondary allocation for them ?

1

There are 1 best solutions below

4
Jarod42 On

From constructor's documentation, emphasize mine:

When the target is a function pointer or a std::reference_wrapper, small object optimization is guaranteed, that is, these targets are always directly stored inside the std::function object, no dynamic allocation takes place. Other large objects may be constructed in dynamic allocated storage and accessed by the std::function object through a pointer.

So, from standard, you have guaranty for function pointer, and std::reference_wrapper (but no ownership for this one).

Else you have to read constructor code of your library/compiler.

For gcc, the condition is (from std_function.h#L124):

static const size_t _M_max_size = sizeof(_Nocopy_types);
static const size_t _M_max_align = __alignof__(_Nocopy_types);

// ...

static const bool __stored_locally =
(__is_location_invariant<_Functor>::value
 && sizeof(_Functor) <= _M_max_size
 && __alignof__(_Functor) <= _M_max_align
 && (_M_max_align % __alignof__(_Functor) == 0));