On 05/04/2011 08:01 AM, zeb wrote:
hi, I have some problem about transfer-ownership. C++ code is like this:

class RefCounter {
    int _count;
public:
     RefCounter() : _count(1) {}
     virtual RefCounter() {}
     void addRef() { ++_count; }
     void release() { --_count; if (_count == 0) delete this; }
};

class A : public RefCounter {...};

class B {
public:
     void setA(A* a) {    // B takes the ownership of A.
         _a = a;
         a.addRef();
     }
private:
     A* _a;
};

So, in python, I use these classes like:
a = A() # the reference count of a is 1 now.
b = B()
b.setA(a) # B take the ownership of A, and now the reference count is 2.
a.release() # a should call release to decrease the reference count, but now
a is invalid. Python says: did not match C++ signature.

I can change the C++ code to solve this problem, but I really don't want to
change C++ code.
It's better to solve it by other way.

Is there any one could give me some advice?

You should really to let Python (and C++, for that matter) handle your reference counting if at all possible.

The best way to do that would be to ensure your Python objects are held inside a smart pointer (boost::intrusive_ptr would probably work). If you set that up correctly, you should never have to call addRef() or release() from your Python code - think of it as allowing Python to always own one reference, which it is responsible for deleting when its done with it.

I realize I'm being a little vague about the details - feel free to ask more questions if you need more help, but a look through the Boost.Python reference documentation for setting the "HeldType" of a class_ instantiation to a smart pointer should get you started.

Good luck!

Jim Bosch





--
View this message in context: 
http://boost.2283326.n4.nabble.com/transfer-ownership-problem-tp3495846p3495846.html
Sent from the Python - c++-sig mailing list archive at Nabble.com.
_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

_______________________________________________
Cplusplus-sig mailing list
Cplusplus-sig@python.org
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to