title: How to reassign `this` pointer inside object member function?
body: <p>I have an interesting question about C++ pointers.</p>
  
  <p>You probably will think that I have to change my design, and avoid
  doing what I am doing, and you are probably right.
  But let's assume that I have a good reason to do it my way.</p>
  
  <p>So this is the situation. I have a C++ class TestClass, and I have a pointer A of this type:</p>
  
  <pre><code>TestClass* A = new TestClass();
  </code></pre>
  
  <p>Among other things TestClass has this function:</p>
  
  <pre><code>void TestClass::Foo(){
      TestClass* B = new TestClass();
      ...
  }
  </code></pre>
  
  <p>This function creates object B of the same type and populates it with some data.</p>
  
  <p>At the end of this function, I want pointer A to point at object B.
  Anywhere outside this function it would look like <strong><code>A=B</code></strong>; inside this function
  it could look like <strong><code>this = B</code></strong><br>
  But as you know you cannot reassign "this" pointer.</p>
  
  <p>Possible solutions:</p>
  
  <ol>
  <li><p>Copy the memory:</p>
  
  <pre><code>memcpy(this, B, sizeof(TestClass));
  </code></pre>
  
  <p>This method works correctly. The function copies each bit of object B into object A.<br>
  Problem: if TestClass is a big object(and it is), it creates significant overhead in performance for multiple Foo calls.</p></li>
  <li><p>Return a B pointer from the function and do something like this</p>
  
  <pre><code>Temp = A;
  A=A-&gt;Foo();
  freeMemory(Temp);
  </code></pre>
  
  <p>But this code looks stupid, and it makes function Foo very hard to use.</p></li>
  </ol>
  
  <p>So the question is, how I can do <strong><code>this = B</code></strong> from inside a member function, without copying whole objects?</p>