问题描述
什么是C和C ++不确定的,不确定的,和实现定义的行为之间的区别?
What is the difference between undefined, unspecified, and implementation-defined behavior in C and C++?
推荐答案
未定义行为的是C和C ++语言的那些方面,可奇怪的程序员1从其他语言(其它语言试图更好地隐藏)。基本上,它是可以编写不以predictable行为方式,即使在节目许多C ++编译器不会报告任何错误的C ++程序!
Undefined behavior is one of those aspects of the C and C++ language that can be surprising to programmers coming from other languages (other languages try to hide it better). Basically, it is possible to write C++ programs that do not behave in a predictable way, even though many C++ compilers will not report any errors in the program!
让我们来看看一个典型的例子:
Let's look at a classic example:
#include <iostream>
int main()
{
char* p = "hello!\n"; // yes I know, deprecated conversion
p[0] = 'y';
p[5] = 'w';
std::cout << p;
}
变量 P
指向字符串你好!\\ n
,以下试两个任务修改字符串。这是什么节目呢?根据第2.14.5 C ++标准的第11段中,它调用的未定义行为的:
The variable p
points to the string literal "hello!\n"
, and the two assignments below try to modify that string literal. What does this program do? According to section 2.14.5 paragraph 11 of the C++ standard, it invokes undefined behavior:
试图修改字符串的效果是不确定的。
我可以听到人们的尖叫声别急,我可以编译这个没有问题,得到输出黄
或你是什么意思不确定,字符串存储在只读存储器,因此第一个任务尝试导致核心转储。这正是与不确定的行为问题。基本上,标准允许你一旦调用未定义行为(甚至鼻魔)发生的任何事情。如果根据语言的你的心理模型一个正确的行为,该模型是完全错误的; C ++标准拥有国内唯一的票,期限。
I can hear people screaming "But wait, I can compile this no problem and get the output yellow
" or "What do you mean undefined, string literals are stored in read-only memory, so the first assignment attempt results in a core dump". This is exactly the problem with undefined behavior. Basically, the standard allows anything to happen once you invoke undefined behavior (even nasal demons). If there is a "correct" behavior according to your mental model of the language, that model is simply wrong; The C++ standard has the only vote, period.
未定义行为的其他例子包括访问超越其边界的数组,,的或写的良好的C ++书籍。螺杆网络教程。螺杆bullschildt。
What can you do to avoid running into undefined behavior? Basically, you have to read good C++ books by authors who know what they're talking about. Screw internet tutorials. Screw bullschildt.
这篇关于未定义的,不确定的,并且实现定义的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!