c++ - 正在将 size_t(大于 int 范围)分配给 int UB?

标签 c++ undefined-behavior

<分区>

在 Linux x86_64 上:

size_t some_constant = std::numeric_limits<size_t>::max();
int my_int = some_constant;
size_t my_size_t = my_int;
cout << (my_size_t == some_constant) << endl;

这会打印 1

这是UB的例子吗?

最佳答案

不是未定义,只是实现已定义。

[conv.integral]

3 If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.

因此,无论您的 C++ 实现做什么,它都必须以某种方式对其进行记录。这也使得它更有可能不会突然中断,因为实现者通常喜欢保持记录的行为不变。

关于c++ - 正在将 size_t(大于 int 范围)分配给 int UB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53263065/

相关文章:

c++ - Win32 更改列表查看项目索引

c++ - CppUtest 在测试之间共享资源, undefined reference

c++ - RapidXML 抛出异常

c - Malloc 返回相同的值 - 没有双重释放错误

c++ - 在巨大的日志文件中搜索数百种模式

c++ - 是否允许编译器优化依赖于具有未声明值的枚举的分支?

c - 为什么我会收到段错误?

rust - Rust 中的严格别名?

c++ - 如果 cout.rdbuf() 用于切换缓冲区并且从不将其设置回去,会出现什么问题?

具有未定义结果的 C 代码,编译器生成无效代码(使用 -O3)