我正在尝试创建一个包含指向该类实例的静态指针列表的类,但我遇到了内存泄漏。我想知道是否有人可以指出以下代码有什么问题。我有一种感觉,要么与析构函数有关,要么与void creature::kill()函数有关。我注意到我正在使用 allegro 但没有包含一些没有做任何特别的功能。
首先是类头:
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();