【问题标题】:Why do instance variables of run-time stack objects differ from heap objects?为什么运行时堆栈对象的实例变量与堆对象不同?
【发布时间】:2013-06-26 06:04:53
【问题描述】:

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

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

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

【问题讨论】:

  • 原因是你没有初始化你的变量,所以允许出现任何随机值。
  • @andre 不是这样。对于 rts 对象,是的,但对于所有堆对象,我得到零。
  • 它被称为“未定义的行为”,它甚至可以在你的鼻子里产生恶魔。
  • @KacyRaye 我知道它是零,但这可能只是运气和不同编译器或操作系统的变化。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    您可以在this similar question的答案中阅读更多内容

    【讨论】:

    • @JohnDibling 你是说Student* heap = new Student; 会自动初始化Student 的成员吗?
    • 我同意约翰的说法,这不是巧合,但我会接受这个答案,因为您提供的链接为我的问题提供了非常全面的答案,所以谢谢!
    • @KacyRaye 你为什么不...赞成这个答案呢?然后我们可以将其标记为重复项。这将有助于未来的 SO 用户。
    猜你喜欢
    • 2015-03-13
    • 2016-02-04
    • 2014-02-28
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2015-09-03
    相关资源
    最近更新 更多