Recently, I am told that declaring an array of lambda functions with reference captures cause Heap allocation. I don't see how this could be true. If true, how and is it possible to do refactoring to avoid Heap Allocation?
For visualization purposes:
std::function<void(void)> func1 = [a few ref captures here](no argument) -> void { ... }
std::function<void(void)> func2 = [a few different ref captures here](no argument) -> void { ... }
std::function<void(void)> func3 = [a few different ref captures here](no argument) -> void { ... }
std::array<std::function<void(void)>, 3U> func_array{ func1, func2, func3 };
CodePudding user response:
You're dynamic allocation comes from your use of std::function<void(void)>
which uses dynamic allocation for type erasure.
You would need to refactor the std::function
s out and that's going to be really hard / potentially impossible to do as your closures have different types.