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

Alex Mohr amohr at pixar.com
Sat May 30 00:48:00 CEST 2015


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.

Also, adding a feature to do it automatically could potentially 
interfere with existing binding code that manually provides 
__copy__/__deepcopy__ methods.

Alex



More information about the Cplusplus-sig mailing list