我在 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时,都会创建一个静态本地数组。
在程序退出时,Marmalade 内存管理器抱怨在此行保留的内存:
siblingFunctions.push_back( FP_ID(funcPtr, newId) );
没有被释放。(事实是我没有清空数组,但我怎么能,我无法在该函数之外访问它!)。
这里有一个问题: Marmalade 只抱怨在第一次调用这个函数时保留的内存!该函数被多次调用,并带有几个不同的模板参数,但抱怨总是只发生在第一次调用时保留的内存。即使我混淆了对该函数的各种调用的顺序,情况也是如此。在自动释放第一个呼叫后为每个呼叫保留的内存 - 我已经检查过了。
那么,现在该怪谁呢?