Order of constructor/destructor invocation

Greg Ewing greg at cosc.canterbury.ac.nz
Thu Mar 7 21:36:46 EST 2002


Björn Lindberg <d95-bli.no at spam.nada.kth.se> wrote:

> Now imagine two resources where one depends on
> the other:
>
> void a_function ()
> {
>       sentry1 s1;
>       sentry2 s2;
>       ...
> }

In Python, reference counting usually sorts this kind
of thing out. If resource2 depends on resource1
somehow, then resource2 probably contains a reference to
resource1, so resource1 will not be freed before
resource2. Sentry objects are not needed, just
keep references to the resources you're using and
drop them when you're finished.

e.g.

  def a_function():
    r1 = get_resource1()
    r2 = get_resource2(r1) # keeps a reference to r1
    do_something()
    # When we return, reference counts on r1 and r2
    # are decremented. It doesn't matter what order
    # this happens in, because r2 also holds a reference
    # to r1, so they can't get freed in the wrong order.

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list