[C++-sig] weak_ptr/shared_from_this and boost.python

Nat Goodspeed ngoodspeed at solidworks.com
Sun Jul 8 18:50:47 CEST 2007


> -----Original Message-----
> From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org]
On
> Behalf Of a_python_coder
> Sent: Saturday, July 07, 2007 4:29 PM
> To: c++-sig at python.org
> Subject: [C++-sig] weak_ptr/shared_from_this and boost.python
> 
> 
> Ive been having a devil of a time trying to get boost python to do the
> right thing when I try to manipulate C++ objects with weak pointers. 

[Nat] Maybe I'm missing something, but where in the short test case do
you mention weak pointers?
 
> /* *************************************************** */
> #include <boost/python.hpp>
> #include <boost/shared_ptr.hpp>
> #include <boost/enable_shared_from_this.hpp>
> 
> using namespace std;
> using namespace boost;
> using namespace python;
> 
> struct XYZ
> 	: public enable_shared_from_this<XYZ>
> {
> 
> 	static shared_ptr<XYZ> construct()
> 	{
> 		s_instance = new XYZ;
> 		shared_ptr<XYZ> xyz( s_instance );
> 		// return a shared_ptr that manages the python object
> 		return extract< shared_ptr<XYZ> >( object(xyz) );

[Nat] I'm floored by the three lines above, especially that last line.

This feels like a modified singleton pattern. What do you want the
lifespan of the managed XYZ object to be? If you want it to persist for
the remainder of the program, why use shared_ptr? If you want it to
vanish when the last outstanding reference has been dropped, why make it
resemble a singleton?

If you're using shared_ptr for some reason other than lifespan
management, it might be simpler to declare s_instance as a
shared_ptr<XYZ> and simply set and return s_instance.

But even if you want to retain the XYZ* s_instance, why wouldn't you
code construct() to set s_instance and then return get()? Why does the
first case behave so very differently from every other case?

> 	}
> 
> 	static shared_ptr<XYZ> get()
> 	{
> 		return shared_ptr<XYZ>( s_instance->shared_from_this()
);
> 	}
> 
> 	static XYZ* s_instance;
> 
> };
> 
> XYZ* XYZ::s_instance = 0;
> 
> 
> BOOST_PYTHON_MODULE( test )
> {
> 	class_<
> 		  XYZ
> 		, shared_ptr<XYZ>
> 		, noncopyable
> 		>( "XYZ", no_init )
> 		;
> 
> 	def( "construct", &XYZ::construct );
> 	def( "get", &XYZ::get );
> 
> }



More information about the Cplusplus-sig mailing list