我不知道爲什麼我在這裏有內存泄漏,真的很感謝任何建議。 注意,在進程終止之前,我調用了destroy(),這是一個應該刪除單例對象的靜態成員函數。刪除一個單例對象時發生內存泄漏,cpp
下面是相關的代碼和的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
爲什麼我有這樣的泄漏?我刪除_singleton
在destroy()
正如我所說,我將不勝感激任何幫助,謝謝!
難道你調用'destroy()'後第二次調用'instance()'嗎?在這種情況下,內存泄漏是可能的 – undefined
您將不得不發佈一個小型可編譯的簡約代碼示例來說明問題。你發佈的代碼*如果使用正確*應該沒有泄漏,但只有*如果*,除非我們看到代碼,否則我們不知道。 –
同時銷燬時,在destroy()方法中取消分配之前,請檢查_singleton是否爲null。 – Abhineet