Thursday 19 September 2013

Returning local variable by copy - how does it work

Returning local variable by copy - how does it work

Given the sample program below, retlocal1 works while retlocal2 doesn't. I
know the rule about not returning a reference or pointer to a local
variable but I was wondering how it works.
When retlocal1 returns it copies its value to EAX? But EAX is a register
with enough space to hold an integer? So how does EAX hold the entire copy
of the std::string (which could of course be a long long string).
There must be something going on under the hood that I don't understand?
This example is C++, but I assume C works exactly in 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;
}

No comments:

Post a Comment