[C++-sig] Boost.Python and lifetime of instances of C++ classes

David Abrahams david.abrahams at rcn.com
Wed Jan 23 21:29:02 CET 2002


----- Original Message -----
From: "Hugo van der Merwe" <s13361562 at bach.sun.ac.za>
To: <c++-sig at python.org>
Sent: Wednesday, January 23, 2002 9:35 AM
Subject: [C++-sig] Boost.Python and lifetime of instances of C++ classes


> I've attached the source for a python extension (test.cpp), and a
> test.py script, that uses it.
>
> Here is the output of the test.py script:
>
> ==========
> k = test.testclass():
> test Constructor called.
> k.printit():
> HELLO!
> l = test.foo()
> l.add(k)
> l.printit():
> HELLO!
> k = 0
> test Destructor called.
> l.printit():
> HELLO!
> ==========
>
> How does this work?

Luck.

> Since "test Destructor called." appears, I'd think
> k has been destroyed/deallocated.

It has.

> Then l.printit() calls k.printit(),
> from C++. Something's odd, possibly even dangerous. Can someone explain
> this?

The memory at the other end of the pointer has been returned to the system,
but it might not have been overwritten. Regardless of what happened, it
doesn't matter because the pointer doesn't even have to be dereferenced in
order to call that member function. You could probably take any random glob
of bits, cast them to (test*), and call that member function on it.

-Dave





More information about the Cplusplus-sig mailing list