James Kanze
11/22/2008 10:49:00 AM
On Nov 21, 9:44 pm, Salt_Peter <pj_h...@yahoo.com> wrote:
> On Nov 21, 2:29 pm, "mlt" <a...@asd.com> wrote:
[...]
> > but is that not the only way to make sure the instance lives
> > after the calling function has returned?
> No, definitely not the way. Its shoddy programming to allocate
> something over there and deallocate somewhere else.
That is, of course, quite simply false. Unless you have a need
to create an object in one place, and destroy it elsewhere,
there's no point in using dynamic allocation. (There are
exceptions, but this is doubtlessly the major use of dynamic
allocation in application level code.)
> Managing the lifetime of an object should either be automatic
> or given to a single manager.
Not really. If you're object really has significant behavior,
it often makes the most sense that it manage it's own lifetime,
once created. In a server, most long lived objects will be
destructed in a transaction manager, during the commit phase;
it's not the transaction manager which creates them. (The
transaction manager does take over to a certain degree rapidly
after creation, but it's not the same instance as the one which
destructs them, unless rollback occurs.) GUI objects may follow
the self-destruct pattern, but often, they will be destroyed by
the owning object, i.e. client code creates the object, then
inserts it into a panel in a window; destruction is ensured by
the panel, when it is destroyed, or possibly it is the
responsibility of whoever removes the object from its containing
element.
Most of the time, if you could use some simple manager, you
shouldn't be using dynamic allocation to begin with.
> In Java, your GC takes care of that while C++ uses a different
> discipline.
Yes and no. Garbage collection doesn't dispose of a window, or
remove it from a panel; in general, garbage collection only
kicks in once the programmer has decided that the object is no
longer needed. (There are exceptions, of course, and they're
frequent enough to make garbage collection useful in C++ as
well. But they don't dominate.)
> Java only uses the stack to store primitives, C++ can use the
> stack to store anything.
More to the point, in C++, objects are copiable and assignable
(unless you forbid it---which you should for any object which
has identity). And you would generally never allocate a
copiable or an assignable object dynamically.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34