What is a reference variable in C++?

后端 未结 12 2111
孤城傲影
孤城傲影 2020-11-22 08:41

What would be a brief definition of a reference variable in C++?

12条回答
  •  既然无缘
    2020-11-22 09:14

    The first paragraph of the Wikipedia article could easily serve as a brief definition:

    In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C.

    And quoting from the same article:

    C++ references differ from pointers in several essential ways:

    • It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.

    • Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.

    • References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.

    • References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.

    Further reading:

    • Wikipedia: Reference C++
    • Cprogramming.com: C++ References
    • Stack Overflow: Difference between pointer variable and reference variable in C++

提交回复
热议问题