[C++-sig] Ownership question.

Nicodemus nicodemus at globalite.com.br
Sun Apr 27 18:35:18 CEST 2003


David Abrahams wrote:

>Nicodemus <nicodemus at globalite.com.br> writes:
>  
>
>>Unfortunately, I don't think you will get a "nice" way to acomplish
>>this, because of how garbage collection works in Python. 
>>    
>>
>
>Not so fast!  See the FAQ:
>http://www.boost.org/libs/python/doc/v2/faq.html#ownership
>
>always-check-the-faq-first-ly y'rs,
>

Sorry, I didn't explain very well what I meant by "nice". 8)

Suppose that A is a class with a public member "int value" and a 
function foo, which takes the ownership of a A* passed to it. After 
exporting them:

 >>> from test import *
 >>> a = A()
 >>> a
<test.A object at 0x008AA830>
 >>> a.value
0
 >>> foo(a)
deleting a
 >>> a
<test.A object at 0x008AA830>
 >>> a.value
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: bad argument type for built-in operation
 >>> a.value = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: bad argument type for built-in operation
 >>>

So you see, the object after the call is no longer valid, which is 
against the normal Python semantics. The caller must know that "foo" is 
a C++ function and that it takes the ownership of the passed object, and 
the user can no longer use the object. I didn't want to imply that 
Boost.Python couldn't export this type of function: just that the result 
wouldn't be "pythonic", that's all. 8)

Regards,
Nicodemus.






More information about the Cplusplus-sig mailing list