title: Why is the copy constructor called twice in this code snippet?
body: <p>I'm playing around with a few things to understand how copy constructors work. But I can't make sense of why the copy constructor is called twice for the creation of <code>x2</code>. I would have assumed it would be called once when the return value of <code>createX()</code> is copied into <code>x2</code>.<br>
  I also looked at a few related questions on SO, but as far as I can tell I couldn't find the same simple scenario as I am asking here.   </p>
  
  <p>By the way, I'm compiling with <code>-fno-elide-constructors</code> in order to see what's going on without optimizations.    </p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct X {
      int i{2};
  
      X() {
          std::cout &lt;&lt; "default constructor called" &lt;&lt; std::endl;
      }
  
      X(const X&amp; other) {
          std::cout &lt;&lt; "copy constructor called" &lt;&lt; std::endl;
      }
  };
  
  X createX() {
      X x;
      std::cout &lt;&lt; "created x on the stack" &lt;&lt; std::endl;
      return x;
  }
  
  int main() {
      X x1;
      std::cout &lt;&lt; "created x1" &lt;&lt; std::endl;
      std::cout &lt;&lt; "x1: " &lt;&lt; x1.i &lt;&lt; std::endl &lt;&lt; std::endl;    
  
      X x2 = createX();
      std::cout &lt;&lt; "created x2" &lt;&lt; std::endl;
      std::cout &lt;&lt; "x2: " &lt;&lt; x2.i &lt;&lt; std::endl;    
  
      return 0;
  }
  </code></pre>
  
  <p>This is the output:</p>
  
  <pre><code>default constructor called
  created x1
  x1: 2
  
  default constructor called
  created x on the stack
  copy constructor called
  copy constructor called
  created x2
  x2: 2
  </code></pre>
  
  <p>Can someone help me what I'm missing or overlooking here?</p>