【发布时间】:2016-07-29 20:50:28
【问题描述】:
有什么方法可以防止 gcc 中的std::function 为更大的函数对象动态分配内存?
我希望以下代码在没有动态分配的情况下工作:
#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 个字节。这似乎要么 A 大于函数对象可用的内部内存,要么 B 是一个普通的错误。
我想知道是否有任何方法可以在不更改 std::function 的签名或创建大量额外包装代码的情况下规避此类行为。
【问题讨论】:
-
标准规定 鼓励实现避免为小的可调用对象使用动态分配的内存,例如,其中 f 是一个只包含一个对象的指针或引用的对象和一个成员函数指针。编译器尽其所能。如果它不符合您的需求,那么...
-
clang + libc++ 在您的示例中没有分配任何内存 (coliru.stacked-crooked.com/a/52505806440111db)
标签: c++ c++11 gcc memory-management std-function