c++ - 初始化指针但未获得相同的零值
问题描述
我的问题是由于在两个单独的编译器中编译下面的代码而产生的。我在 Eclipse Helios 和 Online GDB Compiler 中输入了以下代码行,得到了不同的结果:
int* ptr1 = new int;
int* ptr2 = new int(20);
cout << "Value of ptr1 = " << *ptr1 << "\n";
cout << "Value of ptr2 = " << *ptr2 << "\n";
delete ptr1; // Destroying ptr1
delete ptr2; // Detroying ptr2
对于在线 GDB,结果是:
Value of ptr1 = 0
Value of ptr2 = 20
但是,Eclipse Helios的结果是:
Value of ptr1 = 225472
Value of ptr2 = 20
它只是告诉我ptr1现在在其中包含一些垃圾值而不是零吗?
解决方案
它只是告诉我 ptr1 现在在其中包含一些垃圾值而不是零吗?
是的,该值不保证为零。对于默认初始化,
(强调我的)
否则,什么也不做:具有自动存储持续时间的对象(及其子对象)被初始化为不确定值。
因此,两个编译器的观察结果都是合理的。
推荐阅读
- svg - SVG 动画延迟不起作用 - 立即重复
- javascript - 在 REACT 中将 setState 设置为另一个状态值
- javascript - 将数组分成相等的两半
- php - Laravel 不返回 withInput() 表单值
- javascript - AdonisJS 迁移未在测试数据库上运行
- github-actions - 如何使用 GitHub Actions 维护 Bazel 缓存?
- javascript - PHP CKFinder 应用程序:开始过滤文本更改
- debian - apt update --allow-releaseinfo-change 在不同的 Debian 版本上
- git - 如果我使用 git pull (merge) 并将我的提交压缩到 master 会发生什么?
- gerrit - 在更改中设置状态字段