vendredi 27 octobre 2017

const reference and returned value

Having code

int test(){
   return "5";
}

and

int main(){
   const int & t = test();
   cout << &t << endl;
}

By stantards , we can assign temporary object to const & variables and extend their lifetime to lifetime of const & variable.

Does that mean that const & variable has the same place in memory ( memory address ) as returned value ( temporary object)?

E.g

If i want to return value from func, it gets copied into register and afterwards assigned to variable , which would mean memory place wouldnt be the same, or it was created on stack , and simply const & variable is alias for that place in memory?

Also why is const required , it is just the way c++ implemented it?

Thanks for answers.

Aucun commentaire:

Enregistrer un commentaire