2

我正在尝试创建一个包含指向该类实例的静态指针列表的类,但我遇到了内存泄漏。我想知道是否有人可以指出以下代码有什么问题。我有一种感觉,要么与析构函数有关,要么与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();
4

1 回答 1

4
 creature a;

确认!你有代码调用delete一个生物而不调用new那个生物。为此,您必须始终使用创建creaturesnew并且永远不要在堆栈上创建它们!如果这个生物在它还在范围内时被杀死会发生什么?繁荣。

于 2013-02-25T15:20:35.687 回答