[C++-sig] C++ copy construction and Python object copies

Trigve Siver trigves at yahoo.com
Sun May 31 09:16:57 CEST 2015



> From: Stefan Seefeld <stefan at seefeld.name>

> To: cplusplus-sig at python.org
> Cc: 
> Sent: Saturday, May 30, 2015 12:57 AM
> Subject: Re: [C++-sig] C++ copy construction and Python object copies
> 
> On 29/05/15 06:48 PM, Alex Mohr wrote:
>>  On 5/29/2015 7:28 AM, Stefan Seefeld wrote:
>>>  Python's copy module allows for objects to be copied. The protocol 
> for
>>>  this will look up special method __copy__. It seems to me that this
>>>  would trivially work for C++ objects providing a copy-constructor.
>>>  However, the copy-constructor isn't automatically bound to 
> __copy__.
>>>  While I can certainly add that in user-code, I wonder why this 
> isn't
>>>  done by Boost.Python itself.
>>>  Does anyone know the reasons for this ? Would it seem useful to add 
> that
>>>  feature ?
>> 
>>  The __copy__ method's intended semantics are to produce a 
> "shallow"
>>  copy while the __deepcopy__ method is meant to produce a "deep" 
> copy. 
>>  Given a C++ class with a copy ctor, it's hard to know which is more
>>  appropriate.  For instance, copying a shared_ptr<T> is like a
>>  "shallow" copy but copying a vector<pair<int, float>> 
> is like a deep
>>  copy.  On the other hand copying a vector<shared_ptr<T>> is 
> more like
>>  a shallow copy.
>> 
>>  I wouldn't mind an opt-in convenience utility that adds a __copy__ or
>>  __deepcopy__ method, but given the semantic subtlety, I think trying
>>  to do it automatically is dicey.
> 
> That's a fair point.
> 


I agree with Alex Mohr. Adding some mechanism of implementing the copy using copy constructor would be welcome. But doing it automatically wouldn't be ok. I think that explicit is better than implicit.

Trigve


More information about the Cplusplus-sig mailing list