gpt4 book ai didi

c++ - 使用单例时内存泄漏

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:38:27 24 4
gpt4 key购买 nike

我有一个实现单例设计模式的类。我知道有些人认为这不是个好主意,但它有很大帮助,

无论如何 - 我有内存泄漏,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 时将调用析构函数导致无限循环)。我该如何摆脱这种泄漏?谢谢!

附言这是 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;
}

最佳答案

在 C++ 中实现单例的一种常见方法是使实例成为静态函数 std::unique_ptr<T>在实例 getter 内部,而不是类静态变量。这确保了在程序完成时调用析构函数,并允许您创建一个可以多态访问的实例,例如通过指向抽象基类的指针。

Scott Meyers 在 his "More Effective C++" book 中对此主题进行了很好的讨论。 .

关于c++ - 使用单例时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10572610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com