我在Marmalade SDK下运行以下一段代码。我需要知道,如果有在我的代码或果酱是一个“错误”:非常奇怪的内存泄漏
template <class Return = void, class Param = void*>
class IFunction {
private:
static unsigned int counterId;
protected:
unsigned int id;
public:
//
static unsigned int getNewId() { return counterId++; }
template <class FunctionPointer>
static unsigned int discoverId(FunctionPointer funcPtr) {
typedef std::pair<FunctionPointer, unsigned int> FP_ID;
typedef std::vector<FP_ID> FPIDArray;
static FPIDArray siblingFunctions; // <- NOTE THIS
typename FPIDArray::iterator it = siblingFunctions.begin();
while (it != siblingFunctions.end()) {
if (funcPtr == it->first) return it->second; /// found
++it;
}
/// not found
unsigned int newId = getNewId();
siblingFunctions.push_back(FP_ID(funcPtr, newId)); // <- NOTE THIS
return newId;
}
//
virtual ~IFunction() {}
bool operator<(const IFunction* _other) const {
if (this->id < _other->id) return true;
return false;
}
virtual Return call(Param) = 0;
};
需要注意的是,每次模板类discoverId被调用的第一时间,静态局部阵列创建。
在程序退出,果酱内存管理器抱怨说,记忆在这一行保留:
siblingFunctions.push_back(FP_ID(funcPtr, newId));
没有被释放。 (事实是,我不清空数组,但我怎么可能,我没有访问它的功能以外!)。
这里是渔获:酱抱怨只对内存中保留遇到第一次调用这个函数的!该函数被多次调用并且具有多个不同的模板参数,但抱怨总是只发生在第一次调用时保留的内存。即使我混淆了对此函数的各种调用顺序,情况也是如此。在第一个电话被自动释放之后为每个电话保留的存储空间 - 我检查了这一点。
那么,现在是谁的责任呢?
std :: vector可能会立即为多个元素分配空间,您确定这不仅仅是第一次推动为所有后续推送分配空间的“命中”情况? –
2012-02-10 20:18:39
@JoachimIsaksson我经常使用std :: vector,我之前没有遇到过这个问题。它必须与“模板+静态本地”组合 –
2012-02-10 20:28:28