Reputation: 16865
Is there a way I can implement this without using the new
keyword?
void World::generateChunk(Coordinate coord) {
if(loadedChunks[coord])
delete loadedChunks[coord];
loadedChunks[coord] = new Chunk(coord);
loadedChunks[coord]->generate();
}
loadedChunks is a std::map<Coordinate, Chunk*>
.
Upvotes: 1
Views: 104
Reputation: 51920
Yes, by using a:
std::map<Coordinate, Chunk>
World::generateChunk() would them become:
void World::generateChunk(Coordinate coord)
{
loadedChunks[coord] = Chunk(coord);
loadedChunks[coord].generate();
}
Be aware of the implications of this. There's no destructor call anymore since the existing object is being assigned to. And polymorphism doesn't work anymore (you won't be able to store Chunk
subclasses in loadedChunks
.) Furthermore, at least loadedChunks.size()
objects will always exist; they are not deletable.
Chunk
must also meet the criteria of the standard container classes, like being copy-constructible, assignable, etc. And make sure that those operations work correctly (for example you need to determine whether you need a deep copy or shallow copy.)
Upvotes: 3