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的序列点,经典的