Order of constructor/destructor invocation

Björn Lindberg d95-bli.no at spam.nada.kth.se
Wed Mar 6 09:35:06 EST 2002


Jeremy Bowers wrote:
> 
> Björn Lindberg 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.


Björn



More information about the Python-list mailing list