title: Unexpected destructor call occurs when paired with move constuctor
body: <p>The following code was compiled and run in Visual Studio 2012 Express for Windows Desktop, as a learning exercise.</p>
  
  <pre><code>#include &lt;cstdio&gt;
  
  class X
  {
  public:
      X()  { printf("default constructed\n"); }
      ~X() { printf("destructed\n");}
      X(const X&amp;) { printf("copy constructed\n"); }
      X(X&amp;&amp;) { printf("move constructed\n"); }
      X &amp; operator= (const X &amp;) { printf("copy assignment operator\n"); }
  };
  
  X A() {
      X x;
      return x;
  }
  
  int main() {
      {
          A();
      }
      std::getchar();
  }
  </code></pre>
  
  <p>When compiled with compiler optimizations disabled (/Od), the resulting output indicates that the destructor is called twice. This is a problem given that only one object is constructed. <strong>Why is the destructor being called twice?</strong> Wouldn't this be a problem if the class was managing it own resources?</p>
  
  <pre><code>default constructed
  move constructed
  destructed
  destructed   &lt;&lt;&lt; Unexpected call 
  </code></pre>
  
  <p>I tried a couple of experiments to try and explain the output, but ultimately these didn't lead to any useful explanations.</p>
  
  <p>Experiment 1: When the same code is compiled with optimizations enabled (/O1 or /O2), the resulting output is:</p>
  
  <pre><code>default constructed
  destructed
  </code></pre>
  
  <p>which indicates that the Named Return Value Optimization has elided the call to the move constructor, and masked the underlying problem. </p>
  
  <p>Experiment 2: Disabled the optimization and commented out the move constructor. The output generated was what I expected.</p>
  
  <pre><code>default constructed
  copy constructed
  destructed
  destructed
  </code></pre>