Reference

Reference is an alias for the object with which it has been initialized. It acts like a special kind of pointer: Reference vs pointer parameter:

When a parameter is a reference, the function receives the lvalue of the argument rather than a copy of its value. Because the function knows where the argument resides in memory, the argument value is not copied into the function parameter area.

Use reference for passing parameters by reference to speed up process but don't want to change its content,

returntype Function(const parametertype& parameter);
use pointer if its content will be altered because & symbols in the function call statement helps to aware user.


const reference can be initialized to an object of a different type (provided there is a conversion from the one type to the other) as well nonaddressable values, such as literal constants.
double d;
// legal for const references only
const int &ri1 = d; // equivalent to const int *const pi = d;
const int &ri2 = 1024; // reference to memory address of "1024"
const double &rd = d + 1.0;

To accomplish this the compiler actually generate a temporary object that the reference actually addresses but that the user has no access to.

int temp = d;
const int &ri1 = temp;
Assign ri1 a new value would not change d but would instead change temp. To the user, it is as if the change simply did not work (and it doesn't for all the good it does the user). Constant references don't exhibit this problem because they are read-only. Disallowing non-constant references to objects or values requiring temporaries in general seems a better solution than to allow the reference to be defined but seem not to work.


Pointer reference
int i;
int &ri = &i; // error: ri is of type int, not int*
int *pi = &i;
int *&rpi = pi; // ok: pri is a reference to a pointer


int *&rtpi = &i; // error: temporary pointer must const
int * const & rtpi = &i; // ok: rtpi is reference to const temporary pointer

const int iconst = 1024;
int * const & rtpci = &iconst; // error: pointer to non-const int
// ok: rtpci is reference to const temporary pointer to const int
const int * const & rtpci = &iconst;

// to modify the pointer itself rather than the object pointed
void ptrswap(int*& v1, int*& v2)
{
  int *tmp = v2;
  v2 = v1;
  v1 = tmp;
}
Index