我想要一个包含指向该类实例的指针的静态列表的类,但是出现内存泄漏。我想知道是否有人可以指出下面的代码有什么问题。我有一种感觉,它要么与析构函数,或void creature::kill()
函数。我注意到我正在使用allegro,但没有包含一些没有做任何特殊功能的功能。C++静态对象指针列表和内存泄漏
第一类的头:
class creature{
private:
//some data for other functions
public:
static std::list<creature*> mycreatures;
creature();
~creature();
void kill();
};
类.cpp文件
#include "creature.h"
std::list<creature*>creature::mycreatures;
creature::creature(){
mycreatures.push_back(this);
}
creature::~creature(){
std::list<creature*>::iterator p =
find(mycreatures.begin(),mycreatures.end(),this);
if(p != mycreatures.end()){
mycreatures.erase(p);
}
}
void creature::kill(){
if(mycreatures.size()>0){
std::list<creature*>::iterator it = --mycreatures.end ();
delete (*it);
}
}
和主
#include "creature.h"
void main (void){
creature a;
while(!key[KEY_ESC]){
std::list<creature*>::iterator it;
for(it=a.mycreatures.begin(); it!=a.mycreatures.end(); it++)
{
(*it)->//some other non included functions
}
if(key[KEY_N]){
new creature();
}
if(key[KEY_K]){
a.kill();
}
}
allegro_exit();
}
END_OF_MAIN();
'END_OF_MAIN()'做了什么? – 2013-02-25 14:59:08
https://www.allegro.cc/manual/4/api/using-allegro/end_of_main – BoBTFish 2013-02-25 15:00:30
发生什么事了? – 2013-02-25 15:00:35