mercredi 18 mars 2015

How do (traditional, prior c++11 lvalue-) references work in C++


Pointers are easy. There is some memory which holds an address. To get the (meaningful) value dereferencing returns the value contained by the memory the address points to.


References do somehow something similiar: they hold the "link" to a temporary object. But what happens when I assign or use the reference?



#include <iostream>
using namespace std;
int one(){
return 1;
}
int main()
{
const int &rone = one();
cout << &rone << endl;
return 0;
}


Why does this work? Is this adress the adress of the temporary object?



sh-4.2# g++ -std=c++11 -o main *.cpp
sh-4.2# main
0x7fff9d2a4e74


Where is this adress pointing to? And if it points to the magic temporary object, why cant I just do the following. (I know well that it is a rvalue and that & accepts only lvalues, but why?)



int main()
{
cout << &one() << endl;
return 0;
}


My question goes beyond the programming aspect of c++. It is meant more in a techincal direction how C++ works inside. Primarily I try to understand the rvalue references in the context of the move semantics, which require to understand those traditional references (which I hardly ever use).




Aucun commentaire:

Enregistrer un commentaire