嗨,我目前正在开发第一个面向对象的c++项目,当我使用valgrind检查内存泄漏时,它会输出:
32 (24 direct, 8 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2
==1761165== at 0x4839E86: operator new(unsigned long) (vg_replace_malloc.c:344)
==1761165== by 0x403E5C: Game::Game() (game.cpp:3)
==1761165== by 0x404711: Game::loadGame(std::istream&) (game.cpp:109)
==1761165== by 0x4024B2: main (main.cpp:29)
所以现在我去game.cpp:3来检查发生了什么(在game.cpp:109中,我叫Game * temp_game = new Game),在第3行中,我叫构造函数
Game::Game() : game_entity(new EntityVec) {
}
所以我想在某个时候,我没有释放EntityVec。但是仔细检查我的代码后,尤其是loadGame函数和析构函数:
Game *Game::loadGame(std::istream &in){
Game* temp_game=new Game;
temp_game->game_maze=Maze::read(in);
if (temp_game->game_maze == nullptr) {
delete temp_game;
return nullptr;
}
char c;int x;int y;
EntityControllerFactory* ecfac=EntityControllerFactory::getInstance();
while (in>>c){
Entity* temp_entity=new Entity;
temp_entity->setGlyph(std::string(1,c));
temp_game->addEntity(temp_entity);
if (in >> c) {
EntityController* temp_controller = ecfac->createFromChar(c);
temp_entity->setController(temp_controller);
}
else {
delete temp_game;
return nullptr;
}
if (in >> c) {
temp_entity->setProperties(std::string(1,c));
}
else {
delete temp_game;
return nullptr;
}
if((in>>x)&&(in>>y)){
temp_entity->setPosition(Position(x,y));
}
else {
delete temp_game;
return nullptr;
}
}
return temp_game;
}
Game::~Game(){
delete game_ui;
delete game_gameRules;
delete game_maze;
//delete[] game_entity;
for(Entity* p: *game_entity){delete p;}
//game_entity->clear();
}
如果loadgame失败,我找不到忘了释放游戏的地方(如果loadgame成功并返回了temp_game,则main应该在最后删除它来处理它)。谁能给我一些建议?非常感谢。
最佳答案
每个new
应该有一个对应的delete
。在Game
构造函数中,您可以使用new
创建game_entity
-但析构函数不会删除它(仅删除其“成员”)。
在析构函数中的delete game_entity;
循环之后,需要for
。