Re: Order of destruct of local variables
On Jul 24, 4:15 am, Alberto Ganesh Barbati <AlbertoBarb...@libero.it>
wrote:
JoshuaMaur...@gmail.com ha scritto:
On Jul 22, 2:58 pm, Le Chaud Lapin <jaibudu...@gmail.com> wrote:
Suppose instead that you were the language designer, and someone asked
you to test your intuition to determine the proper order of
destruction. Your choices are:
1. FIFO (born first die first)
2. LIFO (born first die last)
3. Whatever
I contend that a good engineering mindset in the context of
computation should immediately eliminate #3 from consideration. Since
we are talking about construction/deconstruction, we should intuitvely
known that #1 or #2 is the correct answer, *without* experimentation.
Well, programmers versed in garbage collected languages might disagree.
In such languages, not only objects are not necessarily destroyed when
their variables exit from scope, but the order of destruction is
unspecified unless there is a dependency between the objects themselves.
I think this is a misconception. Collection of garbage memory is *not*
destruction[1]. The only GC language I know that also supports
destruction *in the language* does it based on scope and in the same
order as C++. See C#'s 'using' construct for details.
Other GC languages I know don't support destruction at all. If such
functionality is necessary the programmer has to manually supply all
those destory(), dispose(), close() etc. methods and call them when
necessary. Even there the good practice is usually to make these calls
in the opposite order of object construction/acquisition. Below is a
canonical piece of code that does perform guaranteed manual
destruction of two objects in Java. Notice how simple requirements of
scope cause the order of destruction to mimic the one of C++.
Foo foo = new Foo();
try
{
//use foo...
Bar bar = new Bar();
try
{
//use foo and bar...
}
finally
{
bar.close();
}
}
finally
{
foo.destroy();
}
[1] - I am ignoring mostly useless 'finalizers' for simplicity
--
Eugene
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]