Re: Passing Pointers -- where to delete them
On Mar 3, 1:34 am, "jason.cipri...@gmail.com"
<jason.cipri...@gmail.com> wrote:
On Mar 2, 6:30 pm, James Kanze <james.ka...@gmail.com> wrote:
[snip]
If you can do this, why use dynamic allocation?
[snip similar questions]
I do not generally use dynamic allocation, but I can
definitely think of plenty of very specific situations where I
had no other choice:
I can think of one or two cases myself, but the original context
was responding to relative beginner, and your recommendations
for how to manage memory all seemed to concern situations where
you would normally not use dynamic memory to begin with.
1) When using Borland C++ Builder, which requires that all VCL
components are dynamically allocated with 'new', and does not
allow automatic creation of the components.
The obvious answer to that is to change compilers:-).
2) When implementing a class factory, or other similar idioms
that are useful for dynamic creation of objects when you don't
know what you need ahead of time.
But the case of a factory is precisely the case where you do NOT
delete where you new'ed. The case where your recommendation
doesn't hold.
3) When dynamic allocation is the only solution; such as an
application where user actions directly lead to the creation
and destruction of objects, and so you don't know what you
need to have created at compile time.
This is probably the most frequent use of dynamic allocation in
well written code (with "user actions" being understood in its
largest sense---anything which happens outside your code). And
again, it's precisely a case where construction and destruction
don't come in a literal pair; the destruction will occur where
you handle the external event that triggers it (often in the
object itself, i.e. delete this).
This is especially true when you must use references to the
same dynamically created object in many places in your
application, and the containers you are storing them in
(perhaps an std::vector) do not guarantee that their locations
in memory will remain the same (e.g. storing references to
objects in an std::vector<Something>, as opposed to keeping
track of them in an std::vector<Something *>).
I can probably think of more, if I go through the list of
applications I've written and consider when I've had to use
new.
Certainly. Dynamic allocation corresponds to a real necessity.
My point wasn't that it's never appropriate. My point was that
the ways you presented for managing dynamic memory were not
relevant, because they could only be applied in cases where you
normally shouldn't be using dynamic memory.
--
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