c++ - Avoid memory allocation with std::function and member function -
this code illustrating question.
#include <functional> struct mycallback { void fire() { } }; int main() { mycallback cb; std::function<void(void)> func = std::bind(&mycallback::fire, &cb); }
experiments valgrind shows line assigning func
dynamically allocates 24 bytes gcc 7.1.1 on linux.
in real code, have few handfuls of different structs void(void)
member function gets stored in ~10 million std::function<void(void)>
.
is there way can avoid memory being dynamically allocated when doing std::function<void(void)> func = std::bind(&mycallback::fire, &cb);
? (or otherwise assigning these member function std::function
)
unfortunately, allocators std::function
has been dropped in c++17.
now accepted solution avoid dynamic allocations inside std::function
use lambdas instead of std::bind
. work, @ least in gcc - has enough static space store lambda in case, not enough space store binder object.
std::function<void()> func = [&cb]{ cb.fire(); }; // sizeof lambda sizeof(mycallback*), small enough
as general rule, implementations, , lambda captures single pointer (or reference), avoid dynamic allocations inside std::function
technique (it better approach other answer suggests).
keep in mind, work need guarantee lambda outlive std::function
. obviously, not possible, , sometime have capture state (large) copy. if happens, there no way eliminate dynamic allocations in functions, other tinker stl (obviously, not recommended in general case, done in specific cases).
Comments
Post a Comment