c++ -- Undefined behavior

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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值