为什么不编译会导致错误的代码导致未定义的行为 [英] Why doesn't compile issue an error for code that results in undefined behavior

查看:183
本文介绍了为什么不编译会导致错误的代码导致未定义的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,文章通常说如果malloc和delete配对,或者说它是错误的,不要这样做。

For example, articles usually say that if malloc and delete is paired up, or say that it is wrong and don't do it.

但为什么编译器不为我们做一些检查。

But why doesn't compiler do some checking for us.

有没有任何情况下,这种代码是正确的和打算?因此编译器不能总是说错了吗?

Will there be any cases that this kind of code is right and intended? Therefor compiler can't always say it's wrong to do it?

或者,编译器是否有任何技术上的困难?

Or is there any technically difficulties for compiler to do that?

推荐答案


  • 某些未定义的行为可能将定义的效果作为实现特定的扩展。

  • Some undefined behaviour may have defined effects as an implementation specific extension.

一些未定义的行为只发生在程序的环境或输入,所以代码可能会导致未定义的行为,但不一定这样做。

Some undefined behaviour only occurs based on a program's environment or input, so the code might has the potential to cause undefined behaviour but won't necessarily do so.

很多未定义行为的实例很难诊断。可能涉及在后续翻译单元中可能潜在冲突的事物。如果他们很容易诊断,很可能标准需要一个实施来发布诊断,因为它在许多情况下。

Many instances of undefined behaviour are hard to diagnose. The may involve things that might potentially conflict in subsequent translation units. If they were easy to diagnose it is likely that the standard would require an implementation to issue a diagnostic as it does in many cases.

这篇关于为什么不编译会导致错误的代码导致未定义的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆