【问题标题】:C++ Static List of object pointers, and memory leakC++ 静态对象指针列表和内存泄漏
【发布时间】:2013-02-10 18:24:18
【问题描述】:

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

【问题讨论】:

  • END_OF_MAIN() 是做什么的?
  • 有什么事发生吗?
  • 另外,(*it)-&gt;//some other non included functions:这是否意味着您已经分配了一些 creature 实例?
  • @user2103466 任务管理器是一种不可靠的方法来识别泄漏 - C++ 运行时并不总是将释放的内存返回给操作系统。

标签: c++ list pointers memory-leaks


【解决方案1】:
 creature a;

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

【讨论】:

  • 在让我更多地思考 staic 之间,最后一个评论和删除的人,(谢谢)和你关于生物 a 的观点;我摆脱了一个,并直接通过 bio::mycreatures 访问了该列表。和生物::杀。问题好像已经解决了,谢谢大家
猜你喜欢
  • 2013-10-31
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 2019-06-18
  • 2014-09-25
相关资源
最近更新 更多