【发布时间】:2017-02-27 07:10:52
【问题描述】:
#include <iostream>
int Value ()
{
int x = 90;//creates a variable x
return x;//returns the value x, into the caller
//x is destroyed because it is out of scope
}
int * ptr ()
{
int x = 7;//creates variable x
return &x;//returns a pointer to x
//x gets destroyed because it is out of scope
}
主函数内部
int y = Value ();// y = 7
int *py = ptr ();
/* *py = 7, not Undefined Behaviour?? */
我创建了这段代码,在调试程序时,我在我的监视窗口中 *py = 7。 我不应该得到一个未定义的行为,并且程序崩溃,因为 py 指向一个现在有垃圾的地址(ptr() 中的 x 超出范围)
【问题讨论】:
-
UB 的问题是其中一种可能性是它似乎可以工作。尝试更改调用顺序,您很可能会在调用
Value后看到*py更改值。 -
我现在做了,它给了我 0。谢谢
-
这也是非常依赖编译器和操作系统的。这就是 undefined-behavior 的含义,因为它是由实现定义的,而不是保证在任何情况下都能正常工作。
标签: c++ pointers return-value