读取不确定值未定义行为吗?
问题出现在问题答案的评论中 C/C++ bool 类型在类型转换为 int 时是否始终保证为 0 或 1?
The question arose in the comments of an answer to the question Is C/C++ bool type always guaranteed to be 0 or 1 when typecast'ed to int?
有问题的代码分配 bool
的(本地)数组而不初始化它们的值.
The code in question allocates a (local) array of bool
without initializing their value.
const int n = 100;
bool b[n];
显然 b
中的值是不确定的.
Clearly the values in b
are indeterminate.
一些评论者认为阅读例如b[0]
是未定义的行为.这在 C++ 标准中的任何地方都有说明吗?我仍然相信相反的观点:
Some of the commenters opined that reading e.g. b[0]
was undefined behavior. Is this stated anywhere in the C++ standard? I am still convinced of the opposite:
显然已经分配了存储空间,并且基本 bool 类型的初始化已完成,因为它没有构造函数.因此,它肯定与取消引用未初始化的指针或在未初始化的非平凡对象上调用方法/强制转换运算符不同.标准似乎涵盖了这些特定情况.
There is clearly storage allocated and initialization of the fundamental bool type is complete, since it doesn't have a constructor. It is thus certainly not the same as dereferencing an uninitialized pointer, or calling methods/cast operators on uninitialized non-trivial objects. These specific cases seem to be covered by the standard.
C 中的行为确实未定义:C 中声明的、未初始化的变量会发生什么?它有价值吗? 一些受访者似乎混淆了这两者.
The behavior is indeed undefined in C: What happens to a declared, uninitialized variable in C? Does it have a value? and some respondents seem to confuse the two.
在最新的 C++0x 草案中,我找不到 indeterminate value 的定义,尤其是没有允许访问此类值以触发处理器陷阱的定义.事实上,Bjarne Stroustrup 不确定什么是无界值:http://zamanbakshifirst.blogspot.com/2007/02/c-indeterminate-value.html
In the latest C++0x draft I can find no definition of indeterminate value especially no definition that would allow accessing such a value to trigger a processor trap. Indeed, Bjarne Stroustrup is not sure what an inderminate value may be: http://zamanbakshifirst.blogspot.com/2007/02/c-indeterminate-value.html
推荐答案
是的,形式上不确定值的右值转换是 UB(除了 unsigned char
,最初我写了和变体",但作为我记得正式迎合 1 的补码有符号字符,其中可能将负 0 用作陷阱值)
yes, formally an rvalue conversion of indeterminate value is UB (except for unsigned char
, originally i wrote "and variants" but as i recall the formal caters to 1's complement signed char where possibly minus 0 could be used as trap value)
我懒得为你做标准的段落查找,也懒得关心否决票
i'm too lazy to do the standard paragraph lookup for you, and also to lazy to care about downvotes for that
然而,在实践中,问题只存在于 (1) 过时的架构,也许 (2) 64 位系统.
however, in practice only a problem on (1) archaic architectures, and perhaps (2) 64-bit systems.
编辑:哎呀,我现在似乎想起了一篇关于正式 UB 访问不确定字符的博客文章和相关缺陷报告.所以也许我必须实际检查标准,+搜索DR.啊,那得晚点了,现在喝咖啡!
EDIT: oops, i now seem to recall a blog posting and associated Defect Report about formal UB for accessing indeterminate char. so perhaps i'll have to actually check the standard, + search DRs. argh, it will have to be later then, now coffee!
EDIT2:Johannes Schaub 非常友??好地提供了这个 链接到 SO 问题,其中讨论了用于访问 char 的 UB.所以,这就是我记得它的地方!谢谢,约翰内斯.
EDIT2: Johannes Schaub was kind enough to provide this link to SO question where that UB for accessing char was discussed. So, that's where I remembered it from! Thanks, Johannes.
干杯hth.,
相关文章