title: How does the compiler determine the needed stack size for a function with compiler generated temporaries?
body: <p>Consider following code:</p>
  
  <pre><code>class cFoo {
      private:
          int m1;
          char m2;
      public:
          int doSomething1();
          int doSomething2();
          int doSomething3();
  }
  
  class cBar {
      private:
          cFoo mFoo;
      public:
          cFoo getFoo(){ return mFoo; }
  }
  
  void some_function_in_the_callstack_hierarchy(cBar aBar) {
      int test1 = aBar.getFoo().doSomething1();
      int test2 = aBar.getFoo().doSomething2();
      ...
  }
  </code></pre>
  
  <p>In the line where getFoo() is called the compiler will generate a temporary object of cFoo, to be able to call doSomething1().
  Does the compiler reuse the stack memory which is used for these temporary objects?
  How many stack memory will the call of "some_function_in_the_callstack_hierarchy" reservate? Does it reservate memory for every generated temporary?</p>
  
  <p>My guess was that the compiler only reserve memory for one object of cFoo and will reuse the memory for different calls, but if I add </p>
  
  <pre><code>    int test3 = aBar.getFoo().doSomething3();
  </code></pre>
  
  <p>I can see that the needed stack size for "some_function_in_the_callstack_hierarchy" is way more and its not only because of the additional local int variable.</p>
  
  <p>On the other hand if i then replace</p>
  
  <pre><code>cFoo getFoo(){ return mFoo; }
  </code></pre>
  
  <p>with a reference (Only for testing purpose, because returning a reference to a private member is not good)</p>
  
  <pre><code>const cFoo&amp; getFoo(){ return mFoo; }
  </code></pre>
  
  <p>it needs way less stack memory, than the size of one cFoo.</p>
  
  <p>So for me it seems that the compiler reserves extra stack memory for every generated temporary object in the function. But this would be very inefficient.
  Can someone explain this?</p>