c++ - 按值和地址返回

标签 c++ pointers return-value

#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/

相关文章:

c++ - 为什么这里调用复制构造函数,而不是 move 构造函数?

c++ - 从 python 运行 C++ 代码

C++ const 结构指针不可访问

javascript - react-native fetch().then() 返回对象对象

python - 从函数中获取特定值

c++ - 怎么了?悬挂指针?

时间:2019-03-08 标签:c++staticnon-static

函数返回后不改变指针

c - 分配固定字符数组与指针以转换为字符串

mysql - 当 Sequelize.findAll 在另一个文件上时,导出函数不返回数据