title: Placement new to avoid copy constructor
body: <p>I have a simple class that contains a pointer to one of it's own members:</p>
  
  <pre><code>struct X {
      int val;
      int* pVal;
      X(int v) : val(v), pVal(&amp;val) {}
  }
  
  X x(1);
  </code></pre>
  
  <p>I have some code like this:</p>
  
  <pre><code>void foo() {
      doStuffWith(x);
      x = X(2); // completely discard the old value of X, and start again
      doStuffWith(x);
  }
  </code></pre>
  
  <p>I'm worried that when x is reassigned, <code>x.pVal</code> will invalidly point to the member of the temporary <code>X(2)</code> if return value optimization does not occur.</p>
  
  <p>I realize I could write a copy constructor to fix this. However, it seems wasteful to do the copy in the first place, rather than constructing the object in the right spot in memory to begin with.</p>
  
  <hr>
  
  <p>Is it reasonable to use the placement new operator here? Or does this have unintented consequences for destructors?</p>
  
  <pre><code>void foo() {
      doStuffWith(x);
      new (&amp;x) X(2); // completely discard the old value of X, and start again
      doStuffWith(x);
  }
  </code></pre>