我有代碼是爲了做內存管理,但它在我從'活'列表中刪除一個對象並將它放到'死'之一:std :: list的連續使用導致崩潰
class MemoryObject {
private:
static std::list <MemoryObject *> alive, dead;
long references;
public:
MemoryObject() {
alive.push_back(this);
references = 0;
}
static void deepClean() {
clean();
std::list<MemoryObject *>::iterator iterator;
for(iterator = alive.begin(); iterator != alive.end(); iterator ++) {
MemoryObject *object = *iterator;
Log::instance().write(DEBUG_LOG, "\nObject still active at the end of the program, check for memory leaks."
"\nSize: %d",
alive.size());
delete object;
}
alive.clear();
}
void reference() {
references ++;
}
void release() {
references --;
if(references <= 0) {
dead.push_back(this);
alive.remove(this);
}
}
static void clean() {
std::list<MemoryObject *>::iterator iterator;
for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
delete(&iterator);
dead.clear();
}
~MemoryObject() {
clean();
}
};
std::list <MemoryObject *> MemoryObject::alive, MemoryObject::dead;
Eclipse的調試顯示它未能在釋放(),總是在第二列表相關的現場 - 我試圖把它們(alive.remove(this) and dead.push_back(this)
)以不同的順序,這改變不了什麼。然而有趣的是,如果我把在中間的東西他們,就像一個printf()語句,它不會崩潰...
這裏就是我從調用它:
#include <stdlib.h>
#include <stdio.h>
#include "log/log.hpp"
#include "memory/object.hpp"
int main(int argc, char *argv[]) {
MemoryObject foo;
foo.release();
MemoryObject::deepClean();
return 0;
}
在你的'clean'功能你'刪除(迭代器)'。這是不正確的。 –
請顯示你是如何調用這些函數的。 –
請仔細閱讀:[mcve] –