title: Why does the compiler create a variable that's only used once?
body: <p>Consider the following two examples, both compiled with <code>g++ (GCC) 12.1.0</code> targetting <code>x86_64-pc-linux-gnu</code>: <code>g++ -O3 -std=gnu++20 main.cpp</code>.</p>
  <p>Example 1:</p>
  <pre><code>#include &lt;iostream&gt;
  
  class Foo {
  public:
      Foo(){ std::cout &lt;&lt; &quot;Foo constructor&quot; &lt;&lt; std::endl;}
      Foo(Foo&amp;&amp; f) { std::cout &lt;&lt; &quot;Foo move constructor&quot; &lt;&lt; std::endl;}
      Foo(const Foo&amp; f) {std::cout &lt;&lt; &quot;Foo copy constructor&quot; &lt;&lt; std::endl;}
  
      ~Foo() { std::cout &lt;&lt; &quot;Foo destructor&quot; &lt;&lt; std::endl;}
  };
  
  class Baz {
  private:
      Foo foo;
  public:
      Baz(Foo foo) : foo(std::move(foo)) {}
      ~Baz() { std::cout &lt;&lt; &quot;Baz destructor&quot; &lt;&lt; std::endl;}
  };
  
  Foo bar() {
      return Foo();
  }
  
  int main() {
      Baz baz(bar());
      return 0;
  }
  </code></pre>
  <p>Output:</p>
  <pre><code>Foo constructor
  Foo move constructor
  Foo destructor
  Baz destructor
  Foo destructor
  </code></pre>
  <p>Example 2:</p>
  <pre><code>#include &lt;iostream&gt;
  
  class Foo {
  public:
      Foo(){ std::cout &lt;&lt; &quot;Foo constructor&quot; &lt;&lt; std::endl;}
      Foo(Foo&amp;&amp; f) { std::cout &lt;&lt; &quot;Foo move constructor&quot; &lt;&lt; std::endl;}
      Foo(const Foo&amp; f) {std::cout &lt;&lt; &quot;Foo copy constructor&quot; &lt;&lt; std::endl;}
  
      ~Foo() { std::cout &lt;&lt; &quot;Foo destructor&quot; &lt;&lt; std::endl;}
  };
  
  class Baz {
  private:
      Foo foo;
  public:
      Baz(Foo foo) : foo(std::move(foo)) {}
      ~Baz() { std::cout &lt;&lt; &quot;Baz destructor&quot; &lt;&lt; std::endl;}
  };
  
  Foo bar() {
      return Foo();
  }
  
  int main() {
      // DIFFERENCE IS RIGHT HERE
      Foo f = bar();
      Baz baz(f);
      return 0;
  }
  </code></pre>
  <p>Output:</p>
  <pre><code>Foo constructor
  Foo copy constructor
  Foo move constructor
  Foo destructor
  Baz destructor
  Foo destructor
  Foo destructor
  </code></pre>
  <p>So the difference here is that there is an additional instance of <code>Foo</code>, which needs to be handled. I find this difference quite shocking, as my (apparently untrained) eyes would not even consider these pieces of code effectively different. Moreover, a collegue might ask me to turn example 1 into example 2 for readability and suddenly I will be incurring a performance penalty!</p>
  <p>So why are example 1 and 2 so different according to the compiler/C++ spec that the resulting code suddenly needs to copy? Why can the compiler not generate the same code for both cases?</p>