C++ references — strict and clean rules

int i2; int & ri = i2;
Cat c; Cat & rc=c;

#1 keyword — a reference is an *ALIAS* or symlink [1] to another variable

* you can take address-of ri. looks the same as i2 i.e.&ri === &i2
* ri can be a lvalue. looks the same as i2, i.e. “ri=222” === “i2=222”. In fact, this also shows you can never reassign a reference to a second target object (different memory location).
* you never need to deference a reference. ri looks the same as i2, without the deref operator “&”.
* when the target of the ref is a user-defined object, then the ref looks the same as the original handle on the object. See P168 [[24]].
* you can put ri on the RHS when initialize a new ref. ri works the same as i2 the original nonref variable.

[1] unix hardlinks have equal status to each other, unlike reference vs referent

A reference has no “separate identity” because it lacks an observable address. Compiler completely hides whatever address a reference occupies.

A reference must be seated at birth and will never be null or reseated. A reference is like your baby boy (Dabao). He has a mother at birth and can’t change his mother. However, a reference can become “invalid” when referent memory is reclaimed.

* The following two lines won’t work because reference has to
* be initialized at the time of declaration
int &debug_level_ref;
debug_level_ref = level;
– so always initialize references
– because references always need to be initialized there could be no NULL references
– references cannot be re-initialized, i.e. throughout its lifetime it will serve as
an alias to the object it was first initialized with


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s