[C++-sig] Wrappend objects identity problem

David Abrahams dave at boost-consulting.com
Thu Mar 30 17:14:20 CEST 2006


Victor Nakoryakov <nail-mail at mail.ru> writes:

>> I could be wrong, but p is instance of shared_ptr and object is
>> boost::python::object.

Roman is correct.

>
> I thought this way too, but the following code:
>
>> class A
>> {
>> };
>> 
>> boost::shared_ptr<A> ptr;
>> python::object getA()
>> {
>> 	if (!ptr)
>> 		ptr = boost::shared_ptr<A>(new A);

There's no Python object associated with *ptr yet.  That happens the
first time you convert ptr or *ptr to Python.

>> 	return python::object(ptr);

This creates a Python object that holds an A object (*ptr) using a
copy of ptr.

The preservation of identity occurs thereafter, and as long as that
object exists.  For example, if you had done:

  {
    python::object a(ptr);  // Creates a new Python object (call it Q)
                            // containing a copy of ptr

    {
      // Create a "magic" shared_ptr that knows about Q
      boost::shared_ptr<A> p1 = python::extract<boost::shared_ptr<A> >(a);

      // p1 now points at *ptr but manages a reference count on Q
      
      boost::object b(p1);
      
      // b now refers to Q and not to a different Python object
    }
    
    // When we leave this scope, all references to Q will disappear,
    and Q will be destroyed
  }

  python::object c(ptr); // Creates a new Python object (call it R)
                         // containing a copy of Ptr

>> }
>> 
>> void Init()
>> {
>> 	python::class_< A, boost::shared_ptr<A>, boost::noncopyable >( "AClass", python::no_init );
                       ^^^^^^^^^^^^^^^^^^^^

This is unnecessary.  The magic of shared_ptr identity preservation
holds no matter how instances of A are held.

>> 	python::def("getA", &getA);
>> }

It sounds like you want a smart pointer that, when converted to Python
the first time, manages a Python object.  That would make an
interesting addition to Boost.Python.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com




More information about the Cplusplus-sig mailing list