What is the difference between references and normal variable handles in C++?

后端 未结 8 938
一生所求
一生所求 2021-01-22 23:33

If C++, if I write:

int i = 0;
int& r = i;

then are i and r exactly equivalent?

8条回答
  •  日久生厌
    2021-01-22 23:52

    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.

    From Here.

提交回复
热议问题