我有一个类,我在其中实现了singelton 设计模式。我知道有些人认为这不是一个好主意,但它很有帮助,
无论如何 - 我有内存泄漏和 vlagrind 指向我这些行:
_singleton = new Manager(); //Manager::instance() (Manager.cpp:18)
和
Manager::Manager() : _file(new ofstream), _tasks(new map<int, Task *>()),
_idState(new map<int, int>()), _closing(false), _pending(false),
_lock(new pthread_mutex_t), _endLock(new pthread_mutex_t), _cond(new pthread_cond_t),
_flushCond(new map<int, pthread_cond_t *>()), _attr(new pthread_attr_t) {
//The last line is line 25 in Manager::Manager
现在在 Manager 的析构函数中,我无法显式删除它,因为它会创建一个愚蠢的循环(因为在删除 _singleton 时会调用析构函数,从而导致无限循环)。我该如何摆脱这种泄漏?谢谢!
Ps 这里是 Valgrind 的输出:
==17823== 512 bytes in 1 blocks are definitely lost in loss record 2 of 2
==17823== at 0x4C27297: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17823== by 0x40151E: Manager::Manager() (Manager.cpp:25)
==17823== by 0x4014DB: Manager::instance() (Manager.cpp:18)
==17823== by 0x406475: initdevice(char*) (outputdevice.cpp:66)
==17823== by 0x4061D5: main (driver.cpp:21)
==17823==
==17823== LEAK SUMMARY:
==17823== definitely lost: 512 bytes in 1 blocks
= =17823== indirectly lost: 0 bytes in 0 blocks
==17823== possibly lost: 288 bytes in 1 blocks
==17823== still reachable: 0 bytes in 0 blocks
==17823== suppressed: 0 bytes in 0 blocks
另外:这是我创建管理器的代码:
Manager.h:
class Manager {
public:
~Manager();
static Manager * instance();
private:
Manager();
static Manager * _singleton;
};
和实施:
Manager.cpp:
Manager * Manager::_singleton = 0;
Manager * Manager::instance() {
if (!_singleton)
_singleton = new Manager();
return _singleton;
}