The following C++ code outputs:
$ g++ -O3 c.cpp
$ ./a.out
in func: 0x7fff5c1ecaf8
in main: 0x7fff5c1ecaf8
hello
C++ code:
#include <iostream>
using namespace std;
struct C {
string s;
};
C f() {
C c = {.s="hello"};
cout << "in func: " << &c << endl;
return c;
}
int main() {
C obj = f();
cout << "in main: " << &obj << endl;
cout << obj.s << endl;
return 0;
}
I have two questions regarding the code and output above:
- in the function
f
,c
is created on the stack, and upon returningc
, the caller inmain
got a copy ofc
, is it correct? - if "Yes" is the answer to question 1, why the memory address of
c
inf
is the same as the memory address ofobj
inmain
, as they are both0x7fff5c1ecaf8
in the output?