有没有办法来阻止gcc中的std::function
动态分配内存的大功能对象?从gcc分配内存或增加阈值防止std ::函数
我本来期望下面的代码没有动态分配工作:
#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;
}
但是它分配24个字节。据我所知,这是因为指向方法的指针需要16个字节,指向类实例的指针需要8个字节。这似乎是比函数对象可用的内部内存大或B是一个普通的错误。
我想知道是否有任何方法可以绕过这种类型的行为,而无需更改std::function
的签名或创建大量附加包装代码。
标准规定_I实现被鼓励避免为小的可调用对象使用动态分配的内存,例如,其中f是只持有指向对象和成员函数pointer_的指针或引用的对象。编译器尽其所能。如果它不符合你的需求,那么... – skypjack
clang + libC++没有在你的例子中分配任何内存(http://coliru.stacked-crooked.com/a/52505806440111db) – Praetorian