What would be a brief definition of a reference variable in C++?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Page 79 ~ 80 C++ Primer 5th ed.
The first paragraph of the Wikipedia article could easily serve as a brief definition:
And quoting from the same article:
Further reading:
Reference variables (
let a
), just say for easy understanding, another name of variable (let x
), which holds the same exact memory location as that ofx
.int &a = x;
refers that a holds same memory location as that ofx
.For example, say two roommates share the same room. One friends name is
x
and another friends name isa
. Ifa
changes the location of the table placed in the room, from position(x,y,z)
to(x1,y1,z1)
then changes are visible to friendx
as well and vice versa.A reference is an entity that is an alias for another object.
A reference is not a variable as a variable is only introduced by the declaration of an object. An object is a region of storage and, in C++, references do not (necessarily) take up any storage.
As objects and references are distinct groups of entities in C++ so the term "reference variable" isn't meaningful.
It's a variable which references another one:
bar
is now a reference, which is to say thatbar
holds the location of memory wherefoo
lies.See here for more information.
A reference variable and a pointer variable are the exact same thing to the machine (the compiler will generate the same machine code).
The most obvious advantages of using a reference variable over a pointer variable in my knowledge:
In the code below, the left side is using a reference variable, and the right side is using a pointer variable. They are the same thing to the machine, but you see the using reference variable saves you a little bit of typing.