为什么运行时堆栈对象的实例变量与堆对象不同
Why do instance variables of run-time stack objects differ from heap objects?
可能还有其他例子,但这是我刚刚遇到的一个。
#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) {}
};
相关文章:
- 你能重载对象变量名本身返回的内容吗
- 为什么我可以使用 memcpy 将一个对象变量复制到另一个对象变量
- 如何使用std::lower_bound比较对象变量,而不使用第二个对象进行比较
- 将私有对象变量与用户输入的变量进行比较
- 具有已定义操作重载的 C++ 非类型化值对象/变量库
- 如何对对象数组进行排序,而不考虑对象变量类型
- 在功能中设置对象变量
- 如何创建对象变量,以便每次分配新的指针
- C++ FileIO 以读取和写入对象变量
- 私下声明的对象变量的突变器/访问器方法
- C++ 列表中的对象变量在迭代过程中不会更新
- 稍后使用私有对象变量时如何初始化数组(初始化对象后)
- 通过向量更改对象变量的值
- C 全局对象变量内存释放
- 基本数据类型变量 VS 对象变量
- C 复制分配运算符,用于参考对象变量
- c++从列表中移除元素,并将其分配给对象变量
- 我们是否需要在C++中同步局部对象变量
- 点运算符和箭头运算符之间的区别 结构对象变量 在 C 或 C++ 中创建树
- 无法访问在 std 回调中传递的对象变量