Topic: Example in "The C++ Workbook" by Wiene
Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1995/08/04 Raw View
In article 3vtat5INNovr@hubble.asymetrix.com, michaelt@asymetrix.com (Michael Taylor) writes:
>fenster@shadow.cs.columbia.edu (Sam Fenster) wrote:
>>a2675528@athena.rrz.Uni-Koeln.DE (Paul Sponagl) writes:
>>> inline template < class T > void swap(T& a, T& b)
>>> {
>>> a ^=b; b^=a;a ^=b;
>>> }
>>
>>This sets `a' and `b' to zero if they refer to the same object.
>
>Wrong!
>
>Let a = 1001110
>and b = 1001110
>
>a ^= b; // -> a = 0
>b ^= a; // -> b = 1001110
>a ^= b; // -> a = 1001110
Not wrong! (Golly, but I get tired of this.)
'a' and 'b' are not the same object. They are different objects which
happen to have the same value. The invocation
swap(a, a)
sets 'a' to zero. You wouldn't normally write that, but when parameters
are passed around by reference, it can happen without your knowing about it.
---
Steve Clamage, stephen.clamage@eng.sun.com