What is a reference variable in C++?

2018-12-31 12:33发布

问题:

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

回答1:

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.



回答2:

A reference variable provides an alias (alternative name) for a previously defined variable. For example:

float total=100;
float &sum = total;

It means both total and sum are the same variables.

cout<< total;
cout << sum;

Both are going to give the same value, 100. Here the & operator is not the address operator; float & means a reference to float.



回答3:

A reference variable is an alias (an alternate name) for an object. [From the C++ FAQ].



回答4:

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++


回答5:

It\'s a variable which references another one:

int foo;
int& bar = foo;

bar is now a reference, which is to say that bar holds the location of memory where foo lies.

See here for more information.



回答6:

C++ references allow you to create a second name for the a variable that you can use to read or modify the original data stored in that variable

For More Details Visit:

http://www.cprogramming.com/tutorial/references.html

http://www.tutorialspoint.com/cplusplus/cpp_references.htm



回答7:

A Reference variable is an alias for the variable name.

It is different from the pointers in following ways:

  1. You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
  2. Once a reference is initialized to an object, it cannot be changed to point to any another object whereas in case of pointer we can make it point to any other object at any time.
  3. A reference must be initialized the time it is created. Pointers can be made initialized at any time.


回答8:

Reference variables allow two variable names to address the same memory location:

int main()
{
    int var1;

    // var2 is a reference variable, holds same value as var1

    int &var2 = var1;
    var1 = 10;

    std::cout << \"var1 = \" << var1 << std::endl;
    std::cout << \"var2 = \" << var2 << std::endl;
}

Resource: LINK



回答9:

A reference is an alternative label, an alias, for the object it is initialized with. Once a reference is initialized it can not be changed to be an alternative label or alias of some other object. After the initialization the reference or the object variable may be used interchangeably.

A reference has some of the characteristics of a const pointer to an object in that it is initialized when defined. And while what it references or points to can be changed, the reference or the const pointer itself can not be changed. However since a reference is an alternative label or alias it may or may not actually exist as a data object unlike a const pointer which will probably exist unless the compiler can optimize it away. And even if a reference is created as an actual entity by the compiler, that is compiler housekeeping and should be ignored since it officially does not exist much like the man behind the curtain in the Emerald City.

The following code samples gives examples comparing and contrasting reference with pointer and const pointer:

int myInt;           // create a variable of type int, value not initialized
int myInt2 = 3;      // create a second variable of type int with a value of 3
int &rInt = myInt;   // create a reference to the variable of type int, myInt

rInt = 5;            // myInt now has a value of 5, the reference is an alias for myInt
rInt++;              // myInt now has a value of 6, the reference is an alias for myInt
rInt = myInt2;       // myInt now has the same value as myInt2, a value of 3
int *pInt = &rInt;   // pInt points to myInt
(*pInt)++;           // increments myInt
pInt++;              // increments the pointer which formerly pointed to myInt

int &rInt2;          // error C2530: \'rInt2\' : references must be initialized
int *pInt2;          // just fine, uninitialized pointer is ok
int * const pInt3;   // error C2734: \'pInt3\' : const object must be initialized if not extern
int * const pInt4 = &myInt;  // define and initialize const pointer
pInt4 = &myInt2;     //  error C3892: \'pInt4\' : you cannot assign to a variable that is const

There are actually two kinds of references: an lvalue reference and an rvalue reference.

An lvalue reference is the same reference in the C++ language before C++11. An rvalue reference was introduced in C++11 to allow for a reference to a temporary object to assist with doing a move rather than a copy and some other actions where a copy is the wrong approach but a move is the right approach.

For example a comparison of lvalue reference and rvalue reference in the following simple source lines. Because these are int references that means that an assignment of a non-integer value results in the compiler doing a conversion which results in a temporary variable. An rvalue reference can bind to a temporary variable and an lvalue reference can not.

// assign a double to an int causing creation of temporary    
int &rIntd1 = 1.2;   // error C2440: \'initializing\' : cannot convert from \'double\' to \'int &\'
int &&rIntd2 = 1.2;  // warning C4244: \'initializing\' : conversion from \'double\' to \'int\', possible loss of data

rInt = rIntd2;       // myInt from the code above now has a value of 1, 1.2 was truncated when converting from double to int


回答10:

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:

  1. Easy to understand (no address, de-reference all kinds of headache things)
  2. Saves you a tiny bit of typing, adn thus probably less error-prone.

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.

Reference variable           Pointer variable
int a = 1;         ~~~~~~    int a = 1;
int &b = a;        ~~~~~~    int *b = &a;
b = 2;             ~~~~~~    *b = 2;
cout << a << \'\\n\'  ~~~~~~    cout << a << \'\\n\'
==============================================
2                  ~~~~~~    2


回答11:

Reference variables (let a), just say for easy understanding, another name of variable (let x), which holds the same exact memory location as that of x.

int &a = x; refers that a holds same memory location as that of x.

For example, say two roommates share the same room. One friends name is x and another friends name is a. If a changes the location of the table placed in the room, from position (x,y,z) to (x1,y1,z1) then changes are visible to friend x as well and vice versa.



回答12:

A reference is an alternative name for an object. A reference variable provides an alias for previously defined variables. A reference declaration consists of a base type an & a reference variable equated to a variable name.



回答13:

Page 79 ~ 80 C++ Primer 5th ed.

Object: A region of memory that has a type

Variable: Named object or reference

Reference: An alias for another object.