我有一个游戏类、立方体类和一个解决方案类。在我的主要功能中,我正在创建一个游戏对象 g,该游戏对象有一个立方体类型对象数组和一堆解决方案类型对象。在主函数中,在退出之前,我通过调用 delete[] g 来删除对象 g;
我想知道这是否会删除数组和堆栈中的所有对象?或者我还会有内存泄漏吗?
示例代码:
int main(void)
{
Game* g = new Game();
//Do something like addCube by calling functions in game
delete g;
}
游戏构造器:
public: Game()
{
int nx;
cout<<"Enter the number of cubes in the game ";
cin>>nx;
this->numOfCubes=nx;
cubes = new Cube[nx];
this->ref=0;
}
游戏功能示例
void Game::addCube()
{
if(ref<numOfCubes)
{
cubes[ref].getSides();
ref++;
cubes[ref]->Sno = ref;
}
else
cout<<"All the cubes are already in the game"<<endl;
}
最佳答案
如果您谈论的是一组实际对象,那么是的,它们将被正确销毁。如果您有一个指针数组,则必须删除每个对象(假设每个对象都是使用 new
创建的)。
编辑:
好吧,你在这里遇到了麻烦:
int main(void)
{
Game* g = new Game();
//Do something like addCube by calling functions in game
delete[] g;
}
g
不指向一个数组,只是一个实例。所以 delete [] g;
是未定义的行为。它应该只是 delete g;
更好的是,根本不要使用动态分配:
int main(void)
{
Game g;
//Do something like addCube by calling functions in game
// No delete necessary since you're using automatic allocation.
}
至于您的 cubes
数组,您必须删除数组本身,因为它是用 new []
创建的。请务必使用 delete [] cubes;
。但是正如 Blastfurnace 所指出的,您正在 addCube()
中泄漏立方体。我想你正在尝试做一个动态数组,在这种情况下 std::vector
将是你最好的 friend 。
关于c++ - 在 C++ 中删除对象会删除已删除对象中的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20026883/