Consider following 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();
...
}
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?
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
int test3 = aBar.getFoo().doSomething3();
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.
On the other hand if i then replace
cFoo getFoo(){ return mFoo; }
with a reference (Only for testing purpose, because returning a reference to a private member is not good)
const cFoo& getFoo(){ return mFoo; }
it needs way less stack memory, than the size of one cFoo.
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?