Re: Standard containers, polymorphic objects, and memory management.
On Jun 3, 4:36 am, Daniel Pitts
<newsgroup.spamfil...@virtualinfinity.net> wrote:
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 *.
Be careful with the concept of ownership. In most applications,
it doesn't really make sense to have a "world" object which owns
the entity objects, but rather the let the entity objects "own"
themselves. And do Shape objects really require destruction; do
they have a deterministic lifetime. If not, then the simplest
solution is to use a garbage collector, and not worry about it.
Otherwise, I don't think that there's any real problem in having
Entity be responsible for the lifetime of its Shape. But of
course, this will really depend on the actual semantics of the
objects in question. There is no one rule which fits all cases.
Also, I'd prefer (although its not a requirement) to avoid the
"new" operator for a lot of this.
If you're objects are polymorphic, you don't have much choice.
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);
}
Why? Entity objects typically have identity, which means that
they don't support copy or assignment; they usually also have an
arbitrary lifetime. Both of which mean that they should
probably never be allocated other than dynamically.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34