[C++-sig] Best practices for wrapping classes where instance lifecycle is managed by someone else?

Mikael Lind elemel at elemel.se
Fri Jul 9 10:05:25 CEST 2010

I'm using Boost.Python to wrap Box2D, a 2D physics engine written in
C++. The user of Box2D starts by constructing an instance of class
b2World. The b2World class has member functions for creating and
destroying bodies and joints (for constraining the movement of the
bodies). The b2Body class has member functions for creating and
destroying fixtures (for attaching collisions shapes to the body). The
created instances are returned as raw pointers.

Is there a safe and efficient way of associating a Python wrapper
instance with a wrapped C++ instance, where the Python instance
doesn't manage the lifecycle of the C++ instance? I was thinking of
adding a member variable to the C++ class that tracks the Python
wrapper instance if any has been created, and do something intelligent
on destruction of the C++ instance, i.e. marking the Python instance
as invalid. I would like to throw an exception if the user attempts to
access the destructed C++ instance through the invalid Python

Is the above a good approach? If it is, has anyone got any best
practices or recommendations for the implementation?

Mikael Lind

More information about the Cplusplus-sig mailing list