Class &operator=(Class const &other) { Class tmp(other); swap(tmp); return *this; }The swap functionality merely swaps the contents of the current object and another object. The standard std::swap function calls the class's operator= function to swap objects. Newer implementations might use move-operations to increase the speed of the swaping operation, but in both cases some form of the assignment operator must be available. Swapping, however, might be possible when assignemnt isn't. Classes having reference data members usually don't offer assignment operators but swapping might be a well-defined operation.
It is well known that objects can be installed in a block of memory using placement new, using a block of memory the size of the object to construct the object it. This is the foundation of the template function FBB::fswap (fast swap). This swap function merely uses the memory occupied by objects to implement the swapping operation and it may therefore be used with classes having const data members, reference data members, ponters to allocated memory etc, etc. The function simply uses a spare block of memory the size of the object to be swapped. It then uses memcpy(3) to swap the information contained in the two objects, using the spare block of memory as a placeholder.
The function uses partial specializations to optimize the swapping operation for objects of sizes 1, 2, 4 or 8 bytes. It uses memcpy(3) for objects of other sizes.
#include <iostream> #include "../fswap" class Demo { std::ostream &d_out; size_t d_value; public: Demo(std::ostream &out = std::cerr, size_t value = 0) : d_out(out), d_value(value) {} void show(char const *msg) { d_out << msg << ". Value: " << d_value << '\n'; } }; using namespace std; int main() { Demo d1; Demo d2(cout, 12); FBB::fswap(d1, d2); d1.show("This is d1"); // to cerr: 12 d2.show("This is d2"); // to cout: 0 }
A -> B -> C -> Dfast-swapping B and C would result in the following corrupted list:
+------+ | | A -> C -+ +-> B -+ +-> D | | +-------------+However, classes implementing a data structure like a linked-list might still benefit from fast swapping operations: by implementing their own swap member they could first use fast swapping to swap the objects, followed by another fast swap to unswap their `next' pointers.