Analogous question:
int* pintVar;
"Why is the * after int? What is the indirection operator doing there? Why isn't it before the variable name such as in here?"
int intVar = *pintVar;
Well, you see * symbol has multiple meanings. Perhaps you already understand this: Within a compound type name, it signifies a pointer type. Within an expression it signifies an operator. It can be either the unary indirection operator (*pintVar
) or the binary multiplication operator (a * b
).
In the exactly same way, & symbol has multiple meanings. Within a compound type name, it signifies a reference type. Within an expression it signifies an operator. It can be either the unary addressof operator (&intVar
) or the binary bitwise AND operator (a & b
).
So, const T&
is a reference to const T, just like const T*
would be a pointer to const T.
Both reference and pointer are forms of indirection, and are quite smilar. Their differences are:
- Pointers are objects, references are not objects
- Because references are not objects, there is no way to take the address of a reference, and there is no such thing as a pointer to reference or a reference to reference.
- There are also no arrays of references.
- A (non-const) pointer can be assigned to point to another object. A reference is bound to a single object for its entire lifetime.
- Pointer can be null, a reference cannot be.
- You must indirect through a pointer explicitly using an indirection operator. All operations on a reference implicitly indirect through the reference, and apply to the referred object instead.
- Assignment of reference is assignment of the referred object.
- Taking the address of a reference variable is taking address of the referred object.
- Pointers are iterators for arrays; You can do pointer arithmetic to iterate the elements. Adding one to a pointer results in pointer to the successive array element. There is no reference arithmetic. Because of the implicit indirection, adding one to reference adds one to the referred object.
Has this got something to do with binding a constant reference 'exception' to a temporary object 'e'?
There are many right words there, but I don't understand what you are trying to mean by them.
e
is a variable. The type of the variable is const std::exception&
i.e. reference to constant exception. Upon throw, the reference is bound to the exception object that was thrown.