[英]assigning char to int reference and const int reference in C++
I noticed that assigning a char
to a const int&
compiles, but assigning it to a int&
gives a compilation error. 我注意到将
char
分配给const int&
编译,但是将其分配给int&
会导致编译错误。
char c;
int& x = c; // this fails to compile
const int& y = c; // this is ok
I understand that it is not a good practice to do this, but I am curious to know the reason why it happens. 我知道这样做不是一个好习惯,但是我很想知道发生这种情况的原因。
I have searched for an answer by looking for "assigning to reference of different type", "assigning char to a int reference", and "difference between const reference and non-const reference", and came across a number of useful posts ( int vs const int& , Weird behaviour when assigning a char to a int variable , Convert char to int in C and C++ , Difference between reference and const reference as function parameter? ), but they do not seem to be addressing my question. 我通过寻找“分配给不同类型的引用”,“将char分配给int引用”和“ const引用与非const引用之间的区别”来寻找答案,并且遇到了许多有用的帖子( int vs const int& , 将char分配给int变量时出现奇怪的行为 , 在C和C ++中将char转换为int, 引用和const引用之间的区别作为函数参数? ),但它们似乎并没有解决我的问题。
My apologies if this has been already answered before. 我很抱歉,如果以前已经回答过。
int& x = c;
Here an implicit conversion from char
to int
is being performed by the compiler. 此处,编译器正在执行从
char
到int
的隐式转换。 The resulting temporary int
can only be bound to a const
reference. 结果临时
int
只能绑定到const
引用。 Binding to a const int&
will also extend the lifetime of the temporary result to match that of the reference it is bound to. 绑定到
const int&
还可以延长临时结果的寿命,以匹配其绑定到的引用的寿命。
This behaviour is justified in the standard N4527 at 8.5.3/p5.2 References [dcl.init.ref] 在标准N4527的8.5.3 / p5.2参考文献[dcl.init.ref]中证明了此行为。
5 A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:
5对类型“ cv1 T1”的引用由类型“ cv2 T2”的表达式初始化,如下所示:
...
...
5.2 Otherwise, the reference shall be an lvalue reference to a non-volatile const type (ie, cv1 shall be const), or the reference shall be an rvalue reference.
5.2否则,引用应为对非易失性const类型的左值引用(即cv1为const),或者引用应为右值引用。 [ Example:
[示例:
double& rd2 = 2.0; // error: not an lvalue and reference not const int i = 2; double& rd3 = i; // error: type mismatch and reference not const
— end example ]
—结束示例]
The fact that the line 该行的事实
const int& y = c;
creates a temporary and y
binds to the temporary can be verified by the following: 创建一个临时对象,并通过以下方法验证与该临时对象的
y
绑定:
#include <iostream>
int main()
{
char c = 10;
const int& y = c;
std::cout << (int)c << std::endl;
std::cout << y << std::endl;
c = 20;
std::cout << (int)c << std::endl;
std::cout << y << std::endl;
return 0;
}
Output: 输出:
10
10
20
10
The value of y
did not change when the value of c
was changed. 当
c
的值改变时, y
的值没有改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.