gpt4 book ai didi

c++ - 删除单例对象时内存泄漏,cpp

转载 作者:太空宇宙 更新时间:2023-11-04 15:49:44 26 4
gpt4 key购买 nike

我不知道为什么我会在这里发生内存泄漏,非常感谢任何建议。请注意,在进程终止之前,我调用了 destroy(),这是一个应该删除单例对象的静态成员函数。

这里是相关代码和valgrind的messaeg:

Manager.h:
class Manager {
public:
// Constructor/destructor
static Manager * instance();
static void destroy();
~Manager();
// Bunch of functions that I didn't write here

private:
Manager();
static Manager * _singleton;
// Bunch of fields that I didn't write here
};

Manager.cpp:
#include "Manager.h"

Manager * Manager::_singleton = NULL;

Manager * Manager::instance() {
if (_singleton == NULL) {
_singleton = new Manager();
}
return _singleton;
}

void Manager::destroy()
{
delete _singleton;
_singleton = NULL;
}

/*
* Destructor
*/
Manager::~Manager() {
// Deleting all fields here, memory leak is not from a field anyway
}

这是 valgrind 的报告:

==28688== HEAP SUMMARY:
==28688== in use at exit: 512 bytes in 1 blocks
==28688== total heap usage: 12 allocs, 11 frees, 10,376 bytes allocated
==28688==
==28688== 512 bytes in 1 blocks are definitely lost in loss record 1 of 1
==28688== at 0x4C27297: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==28688== by 0x4014CE: Manager::Manager() (Manager.cpp:33)
==28688== by 0x401437: Manager::instance() (Manager.cpp:15)
==28688== by 0x4064E4: initdevice(char*) (outputdevice.cpp:69)
==28688== by 0x406141: main (driver.cpp:21)
==28688==
==28688== LEAK SUMMARY:
==28688== definitely lost: 512 bytes in 1 blocks
==28688== indirectly lost: 0 bytes in 0 blocks
==28688== possibly lost: 0 bytes in 0 blocks
==28688== still reachable: 0 bytes in 0 blocks
==28688== suppressed: 0 bytes in 0 blocks

为什么我会漏气?我在 destroy()

中删除了 _singleton

正如我所说,我将不胜感激任何帮助,谢谢!

最佳答案

这里有几点需要注意。最明显的是:你什么时候调用 Manager::destroy。第二件事是内存 valgrind似乎是在提示 is allocated in the constructor ofManager,您没有向我们展示。如果我们可以相信错误信息(我通常发现 valgrind 在这方面是可靠的,尽管它可以被愚弄),但没有剩余的内存指针;您没有删除对象中的某个字段,或者对象在它的构造函数中分配内存,它不保存在 field 。

最后,通常最好不要销毁单例。单例习语的全部目的是避免顺序初始化问题(至少在 C++ 中——否则,只需声明对象的静态实例就足够了)。销毁对象引入了可能的销毁顺序问题。如果你不破坏它,valgrind 将警告可能的内存泄漏(不是“绝对lost"); 你可以忽略这些警告,或者过滤掉它们。

关于c++ - 删除单例对象时内存泄漏,cpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10596407/

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