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

后端 未结 8 803
一生所求
一生所求 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:48

    The syntax int &r=i; creates another name i.e. r for variable i.hence we say that r is reference to i.if you access value of r,then r=0.Remember Reference is moreover a direct connection as its just another name for same memory location.

    0 讨论(0)
  • 2021-01-22 23:51

    Yep - a reference should be thought of as an alias for a variable, which is why you can't reassign them like you can reassign pointers (and also means that, even in the case of a non-optimizing compiler, you won't take up any additional storage space).

    When used outside of function arguments, references are mostly useful to serve as shorthands for very->deeply->nested.structures->and.fields :)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-22 23:53

    That means that r is another name for i. They will both refer to the same variable. This means that if you write (after your code):

    r = 5;
    

    then i will be 5.

    0 讨论(0)
  • 2021-01-23 00:05

    The Reference is an alias of an object. i.e alternate name of an object. Read this article for more information - http://www.parashift.com/c++-faq-lite/references.html

    0 讨论(0)
  • 2021-01-23 00:06

    A reference is an alias for an existing object.

    0 讨论(0)
提交回复
热议问题