title: Why is clang not optimizing this with NRVO?
body: <p>I'm trying to reason why a reasonably good C++ 11 compiler (clang) is not optimizing this code, and wondering  if anybody here has opinions.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #define SLOW
  
  struct A {
    A() {}
    ~A() { std::cout &lt;&lt; "A d'tor\n"; }
    A(const A&amp;) { std::cout &lt;&lt; "A copy\n"; }
    A(A&amp;&amp;) { std::cout &lt;&lt; "A move\n"; }
    A &amp;operator =(A) { std::cout &lt;&lt; "A copy assignment\n"; return *this; }
  };
  
  struct B {
    // Using move on a sink. 
    // Nice talk at Going Native 2013 by Sean Parent.
    B(A foo) : a_(std::move(foo)) {}  
    A a_;
  };
  
  A MakeA() {
    return A();
  }
  
  B MakeB() {  
   // The key bits are in here
  #ifdef SLOW
    A a(MakeA());
    return B(a);
  #else
    return B(MakeA());
  #endif
  }
  
  int main() {
    std::cout &lt;&lt; "Hello World!\n";
    B obj = MakeB();
    std::cout &lt;&lt; &amp;obj &lt;&lt; "\n";
    return 0;
  }
  </code></pre>
  
  <p>If I run this with <code>#define SLOW</code> commented out and optimized with <code>-s</code> I get </p>
  
  <pre><code>Hello World!
  A move
  A d'tor
  0x7fff5fbff9f0
  A d'tor
  </code></pre>
  
  <p>which is expected.</p>
  
  <p>If I run this with <code>#define SLOW</code> enabled and optimized with <code>-s</code> I get:</p>
  
  <pre><code>Hello World!
  A copy
  A move
  A d'tor
  A d'tor
  0x7fff5fbff9e8
  A d'tor
  </code></pre>
  
  <p>Which obviously isn't as nice. So the question is:</p>
  
  <p>Why am I not seeing a NRVO optimization applied in the "SLOW" case? I know that the compiler is not required to apply NRVO, but this would seem to be such a common simple case.</p>
  
  <p>In general I try to encourage code of the "SLOW" style because I find it much easier to debug.</p>