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;
}
The calling convention will specify how to return values that are too large for a single register. Smallish types might be returned in multiple registers; large types by passing a "hidden" pointer argument to the function, specifying where the returned value should be placed.
If you want to know all the gory details, Wikipedia is a good starting point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With