C++ the good parts — std::swap

Appendix

Appendix A

 

Pointer Rewiring aka Relinking

 

Since a “pointer” is a much-feared word, let’s clarify what is pointer rewiring/relinking. That is the idiom used to speed up nontrivial types moving. You do not move them, you swap their internals.

Let’s visualize this function

// overload for pointers to int
inline void rewire( int * A, int * B ) 
{ 
   int * temp = A ; 
   A = B ; 
   B = temp ; 
}

Watch carefully.

Pointer rewiring START

That is the situation upon entering the rewiring function. Then:

T * temp = a ; 
Pointer rewiring step ONE

And then this:

a = b
Pointer rewiring step TWO

This is where “pointer to A” loses its address. It is rewired to the same value as pointer B. Lastly:

b = temp;
Pointer rewiring step THREE

Now B is rewired to the “value A”. Effectively pointers A and B have exchanged addresses of the values they have been pointing to. The pointers themselves have changed. They have been  “rewired”.