If we return pointers from functions, we can write either
const X* f();
or
X* const f();
,in this way controlling whether the pointer can be reassigned or if the class can be modified internally. But when returning references, these two seems to have the same meaning:
const X& f();
X& const f();
It seems impossible to return a reference where you can modify X, but not re-assign it? And if it is indeed impossible, why should we ever return references when pointers seem potent in this area?
UPDATE: As been pointed out, references cannot be reassigned. However this makes me even more bewildered, as the following code prints 33 55, not 33 33 as I would expect. How does that match with that references cannot be reassigned?
struct X
{
X(int i_) { i = i_;}
int i;
};
struct Y
{
X& get2() {tmp2 = new X(55); return *tmp2;}
X& get() {tmp = new X(33); return *tmp;}
void print () {cout << tmp->i << endl;}
X* tmp;
X* tmp2;
};
int _tmain(int argc, _TCHAR* argv[])
{
Y y;
X& tmp2 = y.get2();
X& tmp = y.get();
y.print();
tmp = tmp2;
y.print();
return 0;
}
It seems impossible to return a reference where you can modify X, but not re-assign it?
References can never be re-assigned. They keep referring the same referent to which they are bound at initialization.
why should we ever return references when pointers seem potent in this area?
Reference usage is more intuitive, the caller of functions can use references simply like variables unlike pointers where the user has to deal with the dereferencing etc.