Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 304
Angus Comber Avatar asked Feb 16 '23 05:02

Angus Comber


1 Answers

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.

like image 179
Mike Seymour Avatar answered Feb 23 '23 17:02

Mike Seymour