title: Return Value Optimization And Initializaton of Heap Allocated Variables
body: <p>When initializing a stack allocated variable from a temporary RVO occurs, but it doesn't when initializing a heap allocated variable.</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  class A
  {
  public:
      A() = default;
  
      A(const A &amp;other)
      {
          cout &lt;&lt; "Copy A!" &lt;&lt; endl;
      }
  
      A(A &amp;&amp;other)
      {
          cout &lt;&lt; "Move A!" &lt;&lt; endl;
      }
  };
  
  A foo()
  {
      return A();
  }
  
  int main()
  {
      A a1 = foo(); //Constructs A only!
      A *a2 = new A(foo()); //Constructs A and moves it
  } 
  </code></pre>
  
  <p>Output:
  Move A!</p>
  
  <p>It seems to me that the compiler is creating A in the stack, getting the pointer to heap allocated memory and then moving A, but why doesn't it just gets the pointer first and <strong>then</strong> passes it to foo, so A can be constructed directly in the heap allocated chunk?</p>
  
  <p>EDIT:
  Compiled with g++ (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 5.3.0, using <code>-O3 -std=c++17</code></p>
  
  <p>EDIT 2:
  Updated to MinGW 7.4.0 and now it optimizes out both the copy and the move.</p>