[C++-sig] Wrappend objects identity problem

Victor Nakoryakov nail-mail at mail.ru
Thu Mar 30 16:48:05 CEST 2006


Kelly Burkhart wrote:
> On 3/30/06, *Victor Nakoryakov* <nail-mail at mail.ru 
> <mailto:nail-mail at mail.ru>> wrote:
> 
> 
>     Furtermore following C++ code:
> 
>      > class A
>      > {
>      > };
>      >
>      > A* ptr = 0;
>      > A* getA()
>      > {
>      >       if (!ptr)
>      >               ptr = new A;
>      >
>      >       return ptr;
>      > }
>      >
>      > void Init()
>      > {
>      >       python::class_< A, boost::noncopyable >( "AClass",
>     python::no_init );
>      >       python::def("getA", &getA,
>     python::return_value_policy<python::reference_existing_object>());
>      > }
> 
> 
>     Produces the same output! What's wrong?
> 
> 
> 
> If  I understand correctly what you're trying to do, nothing's wrong.  
> The underlying C++ object is the same even though the python object has 
> a different address.

Exactly! This is side effect that I try to suppress. It makes impossible 
to comfortably use python, search in list of instances, for example.

> class A
> {
> };
>  
> A* aptr = 0;
> A* getA()
> {
>     if (!aptr)
>         aptr = new A;
>     return aptr;
> }
> std::string tstA( A *p ) {
>     if (p == aptr)
>         return std::string("pointers are the same");
>     else
>         return std::string("pointers are not the same");
> }
>  
> BOOST_PYTHON_MODULE(bptst)
> {
>     class_< A, boost::noncopyable >( "AClass", no_init );
>     def("getA", &getA, return_value_policy<reference_existing_object>());
>     def("tstA", &tstA);
> }
> 
>  >>> from bptst import *
>  >>> a1 = getA()
>  >>> a2 = getA()
>  >>> print tstA(a1)
> pointers are the same
>  >>> print tstA(a2)
> pointers are the same
> 
> 


-- 
Victor (aka nail) Nakoryakov
nail-mail<at>mail<dot>ru

Krasnoznamensk, Moscow, Russia




More information about the Cplusplus-sig mailing list