copy on write

Neil Cerutti neilc at norwich.edu
Fri Jan 13 16:20:49 EST 2012


On 2012-01-13, Evan Driscoll <edriscoll at wisc.edu> wrote:
> On 01/13/2012 10:54 AM, Neil Cerutti wrote:
>> If you've ever implemented operator=, operator+, and operator+=
>> in C++ you'll know how and why they are different.
>
> At the same time, you'd also know that that implementing them
> in such a way that 'a += b' does *not* perform the same action
> as 'a = a + b' is considered very bad-mannered.
>
> In fact, it's often suggested (e.g. in "More Effective C++"'s Item 22, 
> though this is not the main thrust of that section) to implement 
> operator+ in terms of += to ensure that this is the case:
>   MyType operator+ (MyType left, MyType right) {
>       MyType copy = left; copy += right; return copy;
>   }

They perform the same action, but their semantics are different.
operator+ will always return a new object, thanks to its
signature, and operator+= shall never do so. That's the main
difference I was getting at.

>> A C++ programmer would be wondering how either can work on
>> immutable objects, and that's where Python's magical rebinding
>> semantics come into play.
>
> IMO a C++ programmer wouldn't be likely to wonder that much at
> all because he or she wouldn't view the objects as immutable to
> begin with. :-) 'x = 5; x += 1;' makes perfect sense in C++,
> just for a somewhat different reason.

I was thinking of const objects, but you are correct that
immutable isn't really a C++ concept.

-- 
Neil Cerutti



More information about the Python-list mailing list