Order of constructor/destructor invocation

Andreas Kostyrka andreas at mtg.co.at
Tue Mar 12 13:52:17 EST 2002


On Wed, 06 Mar 2002 15:35:06 +0100
Björn Lindberg <d95-bli.no at spam.nada.kth.se> wrote:

> No it's not; it's a completely well-defined feature.
Well, it's so for a value oriented language like C++.

> 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;
> 	...
> }

Well, in Python you would have:
def a_function():
	s1=Sentry1()
	s2=Sentry2()

Now this has quite different semantics than the C++ version above, because in Python anything is a reference:

void a_function() {
   sentry1 *s1;
   sentry2 *s2;

   s1=new sentry1;
   s2=new sentry2;
}

In this case C++ doesn't even call the destructor.

Especially, in the case of references, the lexical sequence of definition is not always the same as the dynamic
sequence of creation.

Consider:

def a_function():
	s1=Sentry1()
	s2=Sentry2()
	s1=Sentry1()

Which is the logical sequence for destructing these things?

Additionally, the destructor in Python is seldom needed, and it's calling time is not specified by design choice.
(Jython doesn't use reference counting, it uses Javas gc.)

> The sentry objects will be created and destroyed in the correct order
> for this kind of use to be possible.

Well, this makes sense for C++ (or even might make sense for say EXPANDED types in Eiffel, etc.), but
it senseless in a reference-based language like Python.

Andreas




More information about the Python-list mailing list