- when we use the term reference, we mean “lvalue reference.”
- A reference type “refers to” another type
- A reference is not an object. Instead, a reference is just another name for an already existing object. It’s very important.
- So all operations on that reference are actually operations on the object.
- We can’t define neither a reference to a reference nor pointer to reference. (虽然有时候看起来好像可以,但那实际上用的还是这个object本身)
- reference and the object must match exactly. With two exceptions.
- one is “
const
reference”.actually no such “const reference”.
- one is “
int i = 1;
int &ri = i;
We bind the reference to its initializer. Because there is no way to rebind a reference, so references must be initialized.
Reference to const
“ri is bound to a temporary object”. (C++ Primer, p62)
- refer to a
const
type.nonconst reference can’t refer to an const type, cause the language ban the way that change the underlying object through reference. - refer to a literal
- const reference can refer to nonconst type, but can’t a nonconst reference to refer a const type.
- can refer to an expression.
not allowed with nonconst reference.
Attention
const reference 只说了 reference 是 const,可没说 the underlying 是什么
with the “temporary” feature, I compile some cases and find:
- when a const reference refer to a const or nonconst variable, they hold same address.
- but when refer to an expression or literal, it have a new address.
terms | means |
---|---|
const reference | abbreviate the phrase “reference to const” |