How do you define (explain) in a formal and strict way what is reference type in C++?
I tried to google, and looked into Stroustrup\'s \"The C++ Programming Language
Regarding
” How do you define (explain) in a formal and strict way what is reference type in C++?
the C++11 standard gives the following formal and strict definition of a reference type in its
§8.3.2/1
” In a declaration T D where D has either of the forms
&attribute-specifier-seqoptD1
&&attribute-specifier-seqoptD1
and the type of the identifier in the declarationT D1is “derived-declarator-type-listT,” then the type of the identifier ofDis “derived-declarator-type-list reference toT.”
However, if you’re more interested in what a C++ reference practically is (apart from the colloquial use of the term), then check the definition of its meaning in an expression,
§5.5
” If an expression initially has the type “reference to
T” (8.3.2, 8.5.3), the type is adjusted toTprior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression
Effectively this means that a reference acts as an alias.
You can think of a reference as an automatically dereferenced const pointer, which explains most of the behavior except that a reference doesn't necessarily occupy storage (the compiler may be able to optimize it away completely).