0

Why the address of temp and res are same? In function of version1. I think variable temp will copy to a temporary variable. The temporary variable will copy to variable res. But in result the address of temp and res are same. what optimization the compiler has done?

string version1(const string&s1, const string& s2){
    string temp= s2 + s1 + s2;
    cout<<"temp in version1 address :"<<&temp<<endl;
    return temp;
}

string s1 = "hello";
string s2 = "world";
string res = version1(s1, s2);
cout<<&res<<endl;
liangsun
  • 37
  • 5
  • Anybody can help me? – liangsun Aug 25 '19 at 02:15
  • Your C++ compiler is very smart. No copy will take place. The compiler logically proves to itself that both `temp` and `res` are really the same object, and the result is, basically, both variables are just aliases for the same object. This is called "return value optimization". That's why the addresses are the same. I seem to recall that C++17 requires the compiler to execute this optimization, in this case. See the linked question for more information. – Sam Varshavchik Aug 25 '19 at 02:18

0 Answers0