Article View: comp.std.c++
Article #1467Re: Example in "The C++ Workbook" by Wiener and Pinson
From: Rob Sartin
Date: Tue, 01 Aug 1995 19:42
Date: Tue, 01 Aug 1995 19:42
49 lines
2264 bytes
2264 bytes
[Followups to comp.lang.c++, this is off-topic for comp.std.c++.]
In article <3vjkij$ctk@engnews2.Eng.Sun.COM>,
Steve Clamage <clamage@Eng.Sun.COM> wrote:
>a2675528@athena.rrz.Uni-Koeln.DE (Paul Sponagl) writes:
>
>>> template < class T >
>>> void swap(T & item1, T & item2)
>>> {
>>> T temp = item1;
>>> item1 = item2;
>>> item2 = temp;
>>> }
>>or do like that
>> inline template < class T > void swap(T& a, T& b)
>> {
>> a ^=b; b^=a;a ^=b;
>> }
>
>I had hoped that this old idea was dead, but I guess it isn't.
Ditto.
Steve gives two reasons why it's bad (only works if operator^=
defined and acts as assumed, doesn't always work even then).
There is at least one more: compiler writers often don't optimize
for this old hack (which worked better than a swap with compilers
that did no optimization). Even for "int" I get worse code on two
modern compilers for the xor hack. Sounds like another example of
a traditional hack whose useful life has past (cf. a recent
comp.compilers discussion on bit counting).
GNU g++ on NeXT generally yields a load address and three move
instructions (memory to register, memory to memory, register to
memory) for the temporary version. For the xor version GNU g++ on
NeXT generally yields a load address, three moves (all memory to
register), and three xor instructions (all with a target in memory).
C/Set++ 3.1.2 on AIX 4.1.3 generally yields two loads and two stores
for the temporary version and three load, three xors, and three
stores for the xor version.
So in addition to having correctness and extensibility problems,
"XOR swapping" turns out to be a poor efficiency hack as well.
Regards,
Rob
Technical Details
Message-ID:
<3vm03h$i5j@digdug.pencom.com>Path:
arc1-ca.pugleaf.net!digdug.pencom.com!sartinReferences:
<3ujj8d$o4m@scapa.cs.ualberta.ca> <9520904.20199@mulga.cs.mu.OZ.AU> <3vj9ak$49m@news.rrz.uni-koeln.de> <3vjkij$ctk@engnews2.Eng.Sun.COM>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!digdug.pencom.com!sartin From: sartin@pencom.com (Rob Sartin) Newsgroups: comp.std.c++,comp.lang.c++ Subject: Re: Example in "The C++ Workbook" by Wiener and Pinson Followup-To: comp.lang.c++ Date: 1 Aug 1995 19:42:41 GMT Organization: Pencom Software, Austin, TX Message-ID: <3vm03h$i5j@digdug.pencom.com> References: <3ujj8d$o4m@scapa.cs.ualberta.ca> <9520904.20199@mulga.cs.mu.OZ.AU> <3vj9ak$49m@news.rrz.uni-koeln.de> <3vjkij$ctk@engnews2.Eng.Sun.COM> NNTP-Posting-Host: frodo.pencom.com