What is definition of reference type?

前端 未结 4 2300
攒了一身酷
攒了一身酷 2020-12-30 17:12

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

4条回答
  •  长情又很酷
    2020-12-30 18:00

    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-seqopt D1
          && attribute-specifier-seqopt D1
    and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T,” then the type of the identifier of D is “derived-declarator-type-list reference to T.”


    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 to T prior 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).

提交回复
热议问题