c++ – Undefined behavior
c++ 标准里定义了未定义行为(undefined behavior),即:
1.3.24 undefined behavior
behavior for which this International Standard imposes no requirements
[ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed.
— end note ]
也就是说,标准对未定义行为产生的结果不做任何要求。于是,含有未定义行为的程序可以做任何事情。有些比较极端的说法,认为未定义行为可以格式化你的硬盘。这很恐怖,但是在极端的情况下也并非不可能。当然标准中描述的未定义行为的可能结果是:
- 忽略这一情况,产生未知的结果(很不幸,这可能真的包含格式化硬盘)
- 按照编译环境约定的方式编译或运行(可以有也可以没有编译warning/error)
- 终止编译或运行(并提供warning /error)
所以,包含未定义行为的程序的结果是不确定的,并且很可能是有害的。包含未定义行为的程序应该被认为是错误的程序。
那么C++中有哪些未定义行为呢?下面有一个不完全的列表(翻译有可能不准确,望见谅):
- 1.9 6 在 signal handler 里修改非
volatile std::sig_atomatic_t类型,且非 lock-free atomic objects 的对象的值。 - 1.9 15 如果对一个 scalar object 的副作用,与对同一个对象的另一个副作用或读操作是无序的。(代替了C++03的序列点,经典的 ++)
- 1.10 21 data race 。在一个线程对某内存地址有写操作时,另一个线程对同一个内存地址有读或写操作。两者至少有一个不是原子操作,

本文介绍了C++标准中的未定义行为,这些行为可能导致程序产生不可预测的结果,包括在信号处理程序中修改特定对象、数据竞争、修改字符串常量等。含有未定义行为的程序应被视为错误的,其后果可能严重。文章列举了C++中多种可能引发未定义行为的情况,涉及内存管理、类型转换、对象生命周期等多个方面。
最低0.47元/天 解锁文章
2034

被折叠的 条评论
为什么被折叠?



