Is there a way to prevent std::function in gcc from dynamically allocating memory for larger function objects?
I would expect the following code to work without dynamic allocation:
#include <functional> #include <iostream> // replace operator new and delete to log allocations void* operator new (std::size_t n) { std::cout << "Allocating " << n << " bytes" << std::endl; return malloc(n); } void operator delete(void* p) throw() { free(p); } class TestPlate { private: int value; public: int getValue(){ return value; } void setValue(int newValue) { value = newValue; } int doStuff(const std::function<int()>& stuff) { return stuff(); } }; int main() { TestPlate testor; testor.setValue(15); const std::function<int()>& func = std::bind(&TestPlate::getValue, &testor); std::cout << testor.doStuff(func) << std::endl; testor.setValue(25); std::cout << testor.doStuff(func) << std::endl; }
However, it allocates 24 bytes. As far as I can tell, this is because a pointer to a method requires 16 bytes, and a pointer to an instance of the class requires another 8 bytes. It seems that A is larger than the internal memory available to the function object, or B is a simple mistake.
I was wondering if there is a way around this type of behavior without changing the signature of std::function or creating a lot of extra shell code.
source share