的阵列所以,我有一个类堆损坏当删除指针
class Room {
public:
Room();
~Room();
tile::Tile* tile[11][7]; // Owned
}
的有一个构造和析构函数,tile::Tile
是一个抽象基类,所以是一个指针。指针数组tile,需要像这样在构造函数中填充。
Room::Room() {
for (std::size_t i = 0; i < 11; ++i) {
for (std::size_t j = 0; j < 7; ++j) {
this->tile[i][j] = new tile::Empty();
}
}
}
从我的理解,我也应该在Room
的析构函数删除这些。
Room::~Room() {
for (std::size_t i = 0; i < 11; ++i) {
for (std::size_t j = 0; j < 7; ++j) {
delete this->tile[i][j];
}
}
}
然而,这样做导致的0xc0000374
返回代码,这是一个堆损坏错误。为什么这个腐败错误发生?
最小例如
class Tile {};
class Empty: public Tile {
public:
Empty() {}
};
class Room {
public:
Tile* tiles[5];
Room() {
for (int i = 0; i < 5; ++i) {
tiles[i] = new Empty();
}
}
~Room() {
for (int i = 0; i < 5; ++i) {
delete tiles[i];
}
}
};
class Maze {
public:
Room rooms[5];
Maze() {
for (int i = 0; i < 5; ++i) {
rooms[i] = Room();
}
}
};
int main() {
Maze maze = Maze();
}
你已经损坏了创建和销毁之间的堆。猜测你做了什么或做什么是不可能的。 – molbdnilo
什么是'tile :: Empty()'? – SomeWittyUsername
由于@molbdnilo说错误在别处。将上面的代码转换成[mcve]并查看它是否仍然发生。 –