[C++-sig] Shared pointers and new objects

David Abrahams dave at boostpro.com
Sun Feb 8 19:01:03 CET 2009


on Sun Feb 01 2009, Eric Jonas <jonas-AT-MIT.EDU> wrote:

> I am trying to return a shared pointer to a class Foo and then 
> test the results in python for equality, but they always seem to fail.
> I've created the following two trivial classes: 
>
> class Foo : public boost::noncopyable
> {
> }; 
>
> typedef boost::shared_ptr<Foo> pFoo_t; 
>
> class FooCreator
> {
> public:
>   pFoo_t createFoo() {
>     pFoo_t ft(new Foo); 
>     intfoo = ft; 
>     return ft; 
>   }

The key is that you have to associate the python object with the
shared_ptr that you're going to return.  The original one that wraps the
Foo object you created didn't have any relationship to a Python object.

Try this:

    pFoo_t createFoo() {
      object o(pFoo_t(new Foo));
      intFoo = extract<pFoo_t>(o);
      return intFoo;
    }


>   
>   pFoo_t getFoo() {
>     return intfoo; 
>   }
>
>   pFoo_t intfoo; 
>
> }; 
>
>
> That I expose with boost::python via: 
>
>   class_<Foo, pFoo_t, boost::noncopyable>("Foo", no_init); 
>   
>   class_<FooCreator>("FooCreator")
>     .def("createFoo", &FooCreator::createFoo)
>     .def("getFoo", &FooCreator::getFoo); 
>
> Yet the following assert fails:
>
> fc = FooCreator()
>
> foo = fc.createFoo()
> foo2 = fc.getFoo()
>
> assert_equal(foo, foo2)
>
> The above assert fails. I've tried using the newest boost::python, I've
> looked through the mailing list archives and even asked on IRC, but I
> still can't figure out which part of this process I'm doing incorrectly.
> I've spent about 20 hours reducing my problem to this test case, and am
> really stumped. 

-- 
Dave Abrahams
BoostPro Computing
http://www.boostpro.com


More information about the Cplusplus-sig mailing list