swap() implementation curiosity

B

bartek

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);
}
};
 
A

Andrew Koenig

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?

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top