很奇怪的内存泄漏

时间:2012-02-10 20:14:11

标签: c++ memory-leaks static marmalade

我在Marmalade SDK下运行以下代码。我需要知道我的代码或Marmalade中是否存在“错误”:

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仅抱怨此函数第一次调用时保留的内存!此函数被多次调用并具有多个不同的模板参数,但抱怨始终仅针对第1次调用时保留的内存。即使我混淆了对此函数的各种调用的顺序,也是如此。在第一个呼叫被自动释放后为每个呼叫保留的内存 - 我已经检查过了。

那么,现在应该责怪谁呢?

1 个答案:

答案 0 :(得分:1)

我不知道“Marmalade”是什么(并且快速搜索这个词预期会发现很多不相关的引用)但是你的代码没有关于static FPIDArray siblingFunctions的资源泄漏:这个对象是在第一次调用函数时构造的。它会在main()退出后的某个时刻被销毁。我似乎记得,使用静态链接破坏对象的顺序与构造对象的顺序相反,但我不确定这是否扩展了函数局部静态。

相关问题