#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?? */
我创建了这段代码,并在调试程序时,我在监 window 口中显示了 *py = 7。 我不应该得到一个未定义的行为,并且程序崩溃,因为 py 指向一个现在有垃圾的地址(ptr() 中的 x 超出范围)
最佳答案
函数ptr返回一个值,即局部变量x的地址。当您结束函数时,内存模型仅将此地址 (&x) 标记为可写,但内存中的实际值不会被删除。 因此,当您查看内存地址 py 的实际值时,您会看到值 7,但当另一个函数请求一些内存时,它可能会更改。
关于c++ - 按值和地址返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42479748/