Order of constructor/destructor invocation
Christian Tanzer
tanzer at swing.co.at
Thu Mar 7 01:09:12 EST 2002
Björn Lindberg <d95-bli.no at spam.nada.kth.se> wrote:
> > > and yes, all *standards* *conformant* compilers will follow this practice.
> >
> > Emphasis mine. That was my point. <wink>
> >
> > On an intuitive level, that's one of those "depend on it when you have
> > no other options" kind of features. Even when the standard specs those
>
> No it's not; it's a completely well-defined feature.
>
> Anyway the OP's original example wouldn't have been a beautiful specimen
> of code in C++ either, but since it was only an example it doesn't
> matter.
>
> A common use for the technique in C++ is so called "sentry"-objects that
> handle resources. A stack allocated object that acquires a lock or a
> file handle for example. The object will be destroyed upon leaving the
> function, and the lock can be released or the file handle closed.
> Elegant and efficient. Now imagine two resources where one depends on
> the other:
>
> void a_function ()
> {
> sentry1 s1;
> sentry2 s2;
> ...
> }
>
> The sentry objects will be created and destroyed in the correct order
> for this kind of use to be possible.
Before this thread I would have agreed that destruction order is
completely well defined. Looking at your example I'm not sure about
one case. What if you write:
void a_function ()
{
sentry1 s1, s2;
...
}
? Will s1 be destructed before s2 by all compilers? Guess, I never
cared about that because I tend to use multiple declarations myself.
--
Christian Tanzer tanzer at swing.co.at
Glasauergasse 32 Tel: +43 1 876 62 36
A-1130 Vienna, Austria Fax: +43 1 877 66 92
More information about the Python-list
mailing list