引用是用于初始化它的对象的替代标签、别名。一旦引用被初始化,就不能将其更改为其他对象的替代标签或别名。初始化后,引用或对象变量可以互换使用。
引用具有指向对象的 const 指针的一些特征,即它在定义时被初始化。虽然它引用或指向的内容可以更改,但引用或 const 指针本身不能更改。但是,由于引用是替代标签或别名,它可能会或可能不会作为数据对象实际存在,这与 const 指针不同,除非编译器可以优化它,否则它可能会存在。即使编译器将引用创建为实际实体,这也是编译器的内务管理,应该被忽略,因为它不像翡翠城幕后的人那样正式存在。
以下代码示例给出了使用指针和常量指针比较和对比引用的示例:
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
实际上有两种引用:lvalue 引用和rvalue 引用。
lvalue 引用与 C++11 之前的 C++ 语言中的引用相同。在 C++11 中引入了 rvalue 引用,以允许引用临时对象以帮助进行移动而不是复制以及复制是错误方法但移动是正确方法的其他一些操作。
例如,以下简单源代码行中左值引用和右值引用的比较。因为这些是int 引用,这意味着非整数值的赋值会导致编译器进行转换,从而产生一个临时变量。 rvalue 引用可以绑定到临时变量,lvalue 引用不能。
// 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