C++ 参考创建语法

C++ Reference Creation Syntax

在 C++ 中创建引用时,为什么编译器请求的是值而不是地址。 例如:

int i;
int &j = i;

有效。

int i;
int &j = *&i;

有效。

int i;
int &j = &i;

不正确。如果你在等同于地址,为什么它要求一个值?

引用是已经存在的对象或函数的别名。在特定情况下,这是一个 左值引用 ,因此它是对左值的引用,对象的地址不是左值。

A reference to T can be initialized with an object of type T, a function of type T, or an object implicitly convertible to T.

考虑到这一点,我们得到的错误,当尝试这个不言自明时:

invalid conversion from ‘int*’ to ‘int’ // from the &i to the &i

但是例如,我们可以这样做:

int i;
int *&&j = &i; // j is an rvalue reference to pointer to int

此外,noted in the comments, you should not confuse the & when it is used in a declaration, and when it is used as an operator (i.e. the address-of-operator)。

您可能会从查看文档中受益:

Reference Initialization and Reference declaration.

why does the compiler request a value

它不请求值。你有错误的心态。它所需要的只是一些标识对象的表达式。变量名i就是这样的表达式

在某些情况下,指定对象的表达式会导致对存储值的访问(例如 i = i + i; 会导致访问)。但并非 每次 使用 i 都会导致其值被读取。因此,例如当引用绑定到它时,i 不需要(实际上不需要)访问它的值。

同样,*&i 并不 总是 访问 i 的值。这是一个表达式,其中 C++ 标准表示 *& 在这里“折叠”以简单地指定 i(有一些细节),但由于使用运算符本身而不会发生访问.