You’re not supposed to treat object pointers as pointers to raw binary data in OOP languages, including C++. Objects are “more than” their representation.
So, for example, swaping two objects by swapping their bytes is incorrect:
template<class T>
void bad_swap(T &a, T &b) // Assuming T is the most-derived type of the object
{
char temp[sizeof(T)];
memcpy(temp, &a, sizeof(a));
memcpy(&a, &b, sizeof(b));
memcpy(&b, temp, sizeof(temp));
}
The only situation, however, in which I can imagine this shortcut causing a problem is when an object contains a pointer to itself, which I have rarely (never?) seen in practice; there may, though, also be other scenarios.
What are some actual (real-world) examples of when a correct swap would break if you performed a bitwise swap?
I can easily come up with contrived examples with self-pointers, but I can’t think of any real-world ones.
I’m going to argue that this is almost always a bad idea except in the specific case where profiling has been done and a more obvious and clear implementation of
swaphas performance problems. Even in that case I would only go with this sort of approach for straight up no-inheritance structures, never for any sort of class. You never know when inheritance will be added potentially breaking the whole thing (possibly in truly insidious ways too).If you want a fast swap implementation perhaps a better choice (where appropriate) is to pimpl the class and then just swap out the implementation (again, this assumes that there are no back-pointers to the owner, but that’s easily contained to the class & impl rather than external factors).
EDIT: Possible problems with this approach: