2013-02-25 59 views
2

我想要一个包含指向该类实例的指针的静态列表的类,但是出现内存泄漏。我想知道是否有人可以指出下面的代码有什么问题。我有一种感觉,它要么与析构函数,或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(); 
+0

'END_OF_MAIN()'做了什么? – 2013-02-25 14:59:08

+0

https://www.allegro.cc/manual/4/api/using-allegro/end_of_main – BoBTFish 2013-02-25 15:00:30

+0

发生什么事了? – 2013-02-25 15:00:35

回答

4
creature a; 

确认!你的代码在生物上呼叫delete,但不会致电该生物的new。为了这个工作,你必须总是创建creature s使用new并且从不在堆栈上创建它们!如果这个生物在范围内被杀死会发生什么?繁荣。

+0

让我想起更多的staic,最后一个评论和删除的人,(谢谢)和你关于生物的观点a;我摆脱了一个,直接通过creat :: mycreatures访问列表。和生物::杀死。它似乎已经解决了这个问题,所以谢谢你们两位 – Deengus 2013-02-25 16:17:21