If I do this :-
class Thing
{
...
void function (const std::string& message);
};
std::list<std::function<void()>> work;
and in some member of “Thing”
work.push_back(std::bind(&Thing::function, this, "Hello"));
Does either the call to std::bind or the use of std::function<> cause any dynamic memory allocation using new or otherwise? Or is all the storage allocated at compile time? If the standard doesn’t say anything, what about in visual studio 2012 as my program will only need to build on there, and for efficiency I probably need to avoid dynamic memory allocations in the place where I am thinking of using this mechanism.
The standard doesn’t specify, but in general it’s easy to see that
std::functionmust allocate memory at least in some cases:On the other hand it’s possible for it to avoid allocation in at least some cases by siting its function object inside a preallocated buffer inside the
functionobject’s footprint; obviously there is a tradeoff as this could make other uses take more stack memory. A good implementation would be able to avoid memory allocation when storing a raw function pointer in afunctionobject, and possibly also for amem_fn, but it’s less likely that it’d do so for abind.For example, libstdc++ (g++) inlines (functor) object pointers, function pointers, and (non-virtual) member function pointers, as well as anything else that’d fit in the same footprint, e.g. stateless functors (
union _Nocopy_types).If you can, by inverting your control flow to accept templated functor objects instead of
functionyou can avoid any extra memory allocation: