title: A way to swap two references in C++
body: <p>this is really about a bad idea of swapping two references. The references are not supposed to be resetable so it is not supposed to be possible. That much i know.</p>
  
  <p>What i want to do, is to swap two references, in a way one would swap two pointers: <strong>the addresses are swapped</strong> but <strong>not the data</strong>. Assume:</p>
  
  <pre><code>int a = 0, b = 1;
  int *pA = &amp;a, *pB = &amp;b;
  std::swap(pA, pB);
  </code></pre>
  
  <p>Now *pA is 1 and *pB is 0, but a is still 0 and b is still 1. This is, however, impossible with references:</p>
  
  <pre><code>int a = 0, b = 1;
  int &amp;rA = a, &amp;rB = b;
  std::swap(pA, pB);
  </code></pre>
  
  <p>Now the references are swapped, but the original values are swapped as well. The only thing i can think of is this:</p>
  
  <pre><code>template &lt;class _Ty&gt;
  struct resetable_ref {
      _Ty &amp;ref;
  
      inline resetable_ref(resetable_ref &amp;r)
          :ref(r.ref)
      {}
  
      inline resetable_ref(_Ty &amp;_ref)
          :ref(_ref)
      {}
  
      inline resetable_ref &amp;operator =(resetable_ref &amp;r)
      {
          if(sizeof(resetable_ref) == sizeof(void*)) // compile-time constant (true)
              *reinterpret_cast&lt;void**&gt;(this) = *reinterpret_cast&lt;void**&gt;(&amp;r);
          else
              memcpy(this, &amp;r, sizeof(resetable_ref)); // optimized away as dead code
          return *this;
      }
  
      inline operator _Ty &amp;()
      {
          return ref;
      }
  };
  
  int a = 0, b = 1;
  resetable_ref&lt;int&gt; rrA(a), rrB(b);
  std::swap(rrA, rrB);
  </code></pre>
  
  <p>Now a is still 0 and b is still 1, and the references inside rrA and rrB are swapped. Pity that it doesn't work without the rather ugly operator =(). At least it works for me in MSVC, not sure if g++ will accept it (but i imagine it should).</p>
  
  <p>The whole reference swap is supposed to be used in an object which is constructed with a reference to another object inside, and i'd like to make a swap() function on them. I'd like to avoid using pointers because of the nice non-nullarity feature of the references. It would also be a nicer design (except for the resetable_ref itself).</p>
  
  <p>Does anyone has a better idea of how to go about it? Can anyone think of some compatibility / undefined behavior issues one could run into with this?</p>
  
  <p>I wrote most of the code without compiling, please bear with me if you notice some typo.</p>
  
  <p><strong>EDIT</strong>: It seems to me that a lot of people is missing the point of the question. I know how to use pointers, or even how to wrap pointers in a nice template. The question is tagged "<em>hack</em>" and that is what is expected. Don't tell me stuff like "don't do it, use pointer" since that is not what i asked. If you don't like the topic, don't answer, but don't downvote the question just because you would use pointer.</p>