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

时间:2013-06-28 12:51:42

标签: c++ object runtime heap instance-variables

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

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

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

2 个答案:

答案 0 :(得分:1)

在这个例子中,我认为在已分配的内存中堆已经归零是巧合。

您可以在this similar question

的答案中阅读更多内容

答案 1 :(得分:0)

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

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