D
Daniel Pitts
I'm trying decide on the best way to structure the memory management in
my program.
I have a class (lets call it World), which contains a collection of
Entity objects.
Entity in turn, contains a pointer a Shape object. Shape is a pure
virtual class.
Now, I'm not sure who should "own" the allocation and deallocation of
the Shapes. It makes sense that World should own the Entity objects
directly, but it seems to complicate matters if I want the Entity
objects to delete (through auto_ptr, or on there own destructor) the
Shape *.
Also, I'd prefer (although its not a requirement) to avoid the "new"
operator for a lot of this. eg, I'd like to do something like this:
World world;
world.addEntity(Entity(new Sphere(sphereParams)));
where you have:
void World::addEntity(Entity &entity) {
entities.push_back(entity);
}
Now, if Entity deletes its shape on destruction, I need to make sure
that the Entity copy constructor uses move semantics, but I'm not sure
that's compatible with std::vector<Entity>. Or I need to make World
accept (and manage) Entity pointers.
I suppose I could also make it so that World manages the Shape object
life-cycle, eg "Shape &shape World::addShape(Shape *shape);".
So, any suggestions on which route I should take?
Thanks,
Daniel.
my program.
I have a class (lets call it World), which contains a collection of
Entity objects.
Entity in turn, contains a pointer a Shape object. Shape is a pure
virtual class.
Now, I'm not sure who should "own" the allocation and deallocation of
the Shapes. It makes sense that World should own the Entity objects
directly, but it seems to complicate matters if I want the Entity
objects to delete (through auto_ptr, or on there own destructor) the
Shape *.
Also, I'd prefer (although its not a requirement) to avoid the "new"
operator for a lot of this. eg, I'd like to do something like this:
World world;
world.addEntity(Entity(new Sphere(sphereParams)));
where you have:
void World::addEntity(Entity &entity) {
entities.push_back(entity);
}
Now, if Entity deletes its shape on destruction, I need to make sure
that the Entity copy constructor uses move semantics, but I'm not sure
that's compatible with std::vector<Entity>. Or I need to make World
accept (and manage) Entity pointers.
I suppose I could also make it so that World manages the Shape object
life-cycle, eg "Shape &shape World::addShape(Shape *shape);".
So, any suggestions on which route I should take?
Thanks,
Daniel.