Connecting Tech Pros Worldwide Help | Site Map

swap() implementation curiosity

bartek
Guest
 
Posts: n/a
#1: Jul 22 '05
Hi,

Consider the following implementation of swap() for some class...

It looks a little bit like a hells-spawn.
Though it should work for every object with continuous memory layout,
wouldn't it? The class also wouldn't need to be a POD, because such
swapping shouldn't make any difference for it, even if it had a non-
trivial copy/assignment...

.... or is it just plain completely wrong?

typedef unsigned char Byte;

struct Something {
// ...
void Swap(Something& other)
{
if (this == &other) return;

// Buffer to hold contents of the object.
Byte buffer[sizeof(Something)];
Byte *src, *dst;

src = reinterpret_cast<Byte*>(this);
dst = buffer;
std::copy(src, src+sizeof(Something), dst);

src = reinterpret_cast<Byte*>(&other);
dst = reinterpret_cast<Byte*>(this);
std::copy(src, src+sizeof(Something), dst);

src = buffer;
dst = reinterpret_cast<Byte*>(this);
std::copy(src, src+sizeof(Something), dst);
}
};

--
:: bartekd [at] o2 [dot] pl

Andrew Koenig
Guest
 
Posts: n/a
#2: Jul 22 '05

re: swap() implementation curiosity


"bartek" <spam.will.eat.itself@o2.pl> wrote in message
news:Xns94DACE8D73A66bartekdqwertyuiopo2p@153.19.2 51.200...
[color=blue]
> Consider the following implementation of swap() for some class...[/color]
[color=blue]
> It looks a little bit like a hells-spawn.
> Though it should work for every object with continuous memory layout,
> wouldn't it? The class also wouldn't need to be a POD, because such
> swapping shouldn't make any difference for it, even if it had a non-
> trivial copy/assignment...[/color]
[color=blue]
> ... or is it just plain completely wrong?[/color]

It's just plain completely wrong.

Consider, for example, a class for which every constructor enters the
address of the object being constructed into a global table, and for which
the destructor removes the object's address from that table. This
implementation of swap would completely screw up such a data structure.


Closed Thread


Similar C / C++ bytes