Given the sample program below, retlocal1 works, but retlocal2 does not. I know the rule that I don’t return a link or pointer to a local variable, but I was wondering how this works.
When retlocal1 returns, does it copy its value to EAX? But is EAX a register with enough space to hold an integer? So, how does EAX store the entire copy of std :: string (which can, of course, be a long, long string).
Something must be happening under the hood, which I don't understand?
This example is C ++, but I assume that C works in exactly the same way?
#include <string> std::string retlocal1() { std::string s; s.append(3, 'A'); return s; } std::string& retlocal2() { std::string s; s.append(3, 'A'); return s; } int main(int argc, char* argv[]){ std::string d = retlocal1(); std::string e = retlocal2(); return 0; }
source share