我有一个Organism
类型的2D对象指针数组,其声明像这样Organism*** organisms;
,并且我有一个函数用另一个数组替换该对象。这是我尝试编写此函数的方式:
void World::SetOrganism(Organism * org, const Position & pos) {
if (pos.x < width && pos.x >= 0 && pos.y < height && pos.y >= 0) {
delete organisms[pos.x][pos.y];
organisms[pos.x][pos.y] = org;
}
}
这就是我调用该函数的方式:
world.SetOrganism(new EmptyTile(this->position, world), this->position);
EmptyTile
继承自Organism
。
问题是我总是在与Exception thrown: read access violation. this->organisms was 0x79E5D62E.
的行上收到此错误delete
。我仍在学习C ++,是否不应该删除该对象以避免内存泄漏?
编辑:
这就是我分配organisms
的方式:
World::World(const int& height, const int& width) {
this->width = width;
this->height = height;
organisms = new Organism * *[width];
for (int i = 0; i < width; i++) {
organisms[i] = new Organism * [height];
for (int j = 0; j < height; j++) {
Position* pos = new Position(i, j);
organisms[i][j] = new EmptyTile(*pos, *this);
delete pos;
}
}
}