为什么允许未定义的行为(而不是不编译/崩溃)? [英] Why is undefined behavior allowed (as opposed to not compiling/crashing)?

查看:91
本文介绍了为什么允许未定义的行为(而不是不编译/崩溃)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解编译器/解释器语言扩展的原因,但是为什么没有有效定义的行为却被允许静默失败/做一些奇怪的事情而不是引发编译器错误?是因为编译器捕获它们的额外困难(不可能或仅是耗时)?

I understand the reasons for compiler/interpreter language extensions but why is behaviour that has no valid definition allowed to fail silently/do weird things rather then throwing a compiler error? Is it because of the extra difficulty(impossible or simply time consuming) for the compiler to catch them)?

P.S.哪些语言具有未定义的行为,哪些没有?

P.S. what languages have undefined behaviour and which don't?

P.P.S.是否存在未定义行为的实例,这些实例并非不可能/花费太长时间才能被编译捕获,如果是,是否存在一些充分的理由/借口.

P.P.S. Are there instances of undefined behaviour which is not impossible/takes too long to catch in compilation and if so are there any good reasons/excuses for those.

推荐答案

未定义行为的概念在诸如C和C ++之类的语言中是必需的,因为检测导致这种情况的条件将是不可能的,或者是代价高昂的.以下面的代码为例:

The concept of undefined behaviour is required in languages like C and C++, because detecting the conditions that cause it would be impossible or prohibitively expensive. Take for example this code:

int * p = new int(0);
// lots of conditional code, somewhere in which we do
int * q = p;
// lots more conditional code, somewhere in which we do
delete p;
// even more conditional code, somewhere in which we do
delete q;

此处指针已被删除两次,从而导致未定义的行为.对于像C或C ++这样的语言,很难检测到错误.

Here the pointer has been deleted twice, resulting in undefind behaviour. Detecting the error is too hard to do for a language like C or C++.

这篇关于为什么允许未定义的行为(而不是不编译/崩溃)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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