[英]Is it safe to bind an unsigned int to a signed int reference?
After coming across something similar in a co-worker's code, I'm having trouble understanding why/how this code executes without compiler warnings or errors.在同事的代码中遇到类似的东西后,我很难理解为什么/如何在没有编译器警告或错误的情况下执行此代码。
#include <iostream>
int main (void)
{
unsigned int u = 42;
const int& s = u;
std::cout << "u=" << u << " s=" << s << "\n";
u = 6 * 9;
std::cout << "u=" << u << " s=" << s << "\n";
}
Output: Output:
u=42 s=42
u=54 s=42
First, I expect the compiler to issue some kind of diagnostic when I mix signed/unsigned integers like this.首先,当我像这样混合有符号/无符号整数时,我希望编译器发出某种诊断。 Certainly it does if I attempt to compare with
<
.如果我尝试与
<
进行比较,当然可以。 That's one thing that confuses me.这是让我困惑的一件事。
Second, I'm not sure how the second line of output is generated.其次,我不确定 output 的第二行是如何生成的。 I expected the value of
s
to be 54. How does this work?我预计
s
的值为 54。这是如何工作的? Is the compiler creating an anonymous, automatic signed integer variable, assigning the value of u
, and pointing the reference s
at that value?编译器是否正在创建一个匿名的、自动签名的 integer 变量,分配
u
的值,并将引用s
指向该值? Or is it doing something else, like changing s
from a reference to a plain integer variable?还是它在做其他事情,比如将
s
从引用更改为普通变量 integer?
References can't bind to objects with different type directly.引用不能直接绑定到不同类型的对象。 Given
const int& s = u;
给定
const int& s = u;
, u
is implicitly converted to int
firstly, which is a temporary and then s
binds to the temporary int
. ,
u
首先隐式转换为int
,这是一个临时的,然后s
绑定到临时的int
。 (Lvalue-references to const
(and rvalue-references) could bind to temporaries.) The lifetime of the temporary is prolonged to the lifetime of s
, ie it'll be destroyed when get out of main
. (对
const
的左值引用(和右值引用)可以绑定到临时对象。)临时对象的生命周期延长到s
的生命周期,即离开main
时它将被销毁。
Both int
and unsigned int
are stored in the memory as 4 bytes with total of 32-bits (May vary according to the used compiler) to represent their values in binary form of base-2. int
和unsigned int
都存储在 memory 中,为 4 字节,总共 32 位(可能因使用的编译器而异),以二进制形式表示它们的值。
The main difference between them is that the regular int
reserves the most significant bit (The 32 nd bit) for the sign magnitude where:它们之间的主要区别在于,常规
int
为符号幅度保留了最高有效位(第32位),其中:
0 means positive integer and 1 mean negative integer. 0 表示正 integer,1 表示负 integer。
and therefore int
can carry values up to 2^31
of positive and negative integers.因此
int
可以携带最多2^31
个正整数和负整数的值。
while the unsigned int
uses the whole 32-bits allowing the variable to carry 2^32
而
unsigned int
使用整个 32 位,允许变量携带2^32
Which is the double of what a normal int
can hold.这是普通
int
可以容纳的两倍。 So exchanging values between int
and unsigned int
is fine as long as the value is positive and less than or equal to 2^31
assigning larger or negative values is possible but it will cause overflow and assign values that are different from the expected ones.因此,在
int
和unsigned int
之间交换值是可以的,只要该值为正且小于或等于2^31
即可分配更大或负的值,但它会导致溢出并分配与预期值不同的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.