Re: Simple const-related question
On Feb 19, 3:26 am, Jeff Schwab <j...@schwabcenter.com> wrote:
Kira Yamato wrote:
On 2008-02-18 20:05:51 -0500, Jeff Schwab <j...@schwabcenter.com> said:
I don't usually use the parentheses, either, but I guess I
probably should. I also don't usually allocate objects
directly with new.
Just curious. Instead of directly using new, what do you
usually use to allocate objects?
Either the stack (sorry, "auto" storage) or one of the
standard containers.
The stack is fine for objects whose lifetime corresponds to a
scope. It doesn't work for objects with arbitrary lifetimes.
And the standard containers all require that the object be
copiable---it's very rare for an object that you'd want to
allocate dynamically to support copy. (If it supported copy,
you'd just allocate it on the stack, passing out copies of it,
rather than maintaining that particular instance alive after
scope has been left.)
If I have dynamically allocated objects, I generally have to
store pointers to them somewhere anyway, so I let standard
containers deal with managing their lifetimes.
Except that if the standard container contains pointers, it
won't (and usually shouldn't) manage their lifetime.
For example, if I'll need an unknown quantity of Foos, I just
create a std::list<Foo> and use its elements. Inserting or
deleting list elements does not invalidate pointers to the
other elements.
In my experience, most dynamically allocated objects are entity
objects. That means that they don't support copy, and so cannot
be put into a list. And of course, they're often polymorphic as
well.
--
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