为什么运行时堆栈对象的实例变量与堆对象不同

Why do instance variables of run-time stack objects differ from heap objects?

本文关键字:对象 变量 实例 运行时 堆栈 为什么      更新时间:2023-10-16

可能还有其他例子,但这是我刚刚遇到的一个。

#include <iostream>
using namespace std;
class Student
{
  public:
    int x; 
};
int main()
{
  Student rts;
  Student* heap = new Student;
  cout << rts.x   << endl; // prints out random integer
  cout << heap->x << endl; // prints out 0
}

这背后有什么好的理由或逻辑可以理解吗?

在这种情况下,我认为堆在分配的内存中已经为零只是巧合。

您可以在这个类似问题的答案中阅读更多信息

始终将变量初始化为有意义的值。否则允许随机取任何值。

class Student {
public:
    int x;
Student(): x(0) {}
};