std::function and dynamic memory allocation
std::function needs to store all variables and references that a lambda captures. This behavior is implementation-defined, and implementations usually use heap, which is dynamic memory allocation to store large amounts of variables. If the captured data is small (on some platforms, 16 bytes), it will be stored on the stack. This is called small object optimization. To demonstrate the behavior of the std::function class template when capturing data, we will go through the following example:
#include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <functional>
void *operator new(std::size_t count) {
printf("%s, size = %ld\r\n", __PRETTY_FUNCTION__, count);
return std::malloc(count);
}
void operator delete(void *ptr) noexcept {
printf("%s\r\n", __PRETTY_FUNCTION__);
std::free(ptr);
}
int main () {
std::function<void()> func;
auto arr = []() {
constexpr std...