具有未初始化指针的类是否具有未定义的行为?

发布于 2024-09-13 09:19:58 字数 136 浏览 2 评论 0原文

class someClass
{
public:
    int* ptr2Int;
};

这是一个有效的类吗(是的,它可以编译)?假设在取消引用 ptr2Int 之前为其赋值,该类是否能保证按预期工作?

class someClass
{
public:
    int* ptr2Int;
};

Is this a valid class (yes it compiles)? Provided one assigns a value to ptr2Int before dereferencing it, is the class guaranteed to work as one would expect?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

世界如花海般美丽 2024-09-20 09:19:58

类内未初始化的指针与独立的未初始化指针没有任何区别。只要您不以任何危险的方式使用指针,就没有问题。

请记住,使用未初始化指针的“危险方式”包括仅仅尝试读取其值(无需取消引用)。如果您在为指针分配有效值之前使用这些隐式成员函数,则类中存在的隐式编译器提供的复制构造函数和复制赋值运算符可能会执行此类尝试。

事实上,如果我没记错的话,这个问题是标准化委员会层面上的一些讨论的问题。隐式生成的成员函数是否允许绊倒可能存在于类的非初始化成员中的陷阱表示?我不记得判决是什么了。 (或者也许我在 C99 的背景下看到了这个讨论?)

An uninitialized pointer inside a class is in no way different from a standalone uninitailized pointer. As long as you are not using the pointer in any dangerous way, you are fine.

Keep in mind though that "dangerous ways" of using an uninitialized pointer include a mere attempt to read its value (no dereference necessary). The implicit compiler-provided copy-constructor and copy-assignment operators present in your class might perform such an attempt if you use these implicit member functions before the pointer gets assigned a valid value.

Actually, if I'm not mistaken, this issue was a matter of some discussion at the level of the standardization committee. Are the implicitly generated member functions allowed to trip over trap representations possibly present in the non-initialized members of the class? I don't remember what was the verdict. (Or maybe I saw that discussion in the context of C99?)

猫性小仙女 2024-09-20 09:19:58

是的,没关系。指针本身存在,只是它的值未知,因此取消引用它是不安全的。有一个未初始化的变量是完全可以的,指针也没有什么不同

Yes, it's fine. The pointer itself exists, just its value is just unknown, so dereferencing it is unsafe. Having an uninitialized variable is perfectly fine, and pointers aren't any different

白首有我共你 2024-09-20 09:19:58

是的,这与带有单个未初始化指针的 struct 完全相同,并且两者都保证可以正常工作(当然,只要您在使用指针之前设置指针)。

Yes, this is exactly the same as a struct with a single uninitialized pointer, and both are guaranteed to work just fine (as long as you set the pointer before any use of it, of course).

笑咖 2024-09-20 09:19:58

在取消引用指针之前一切都很好,然后它就是未定义的区域。

某些编译器会将指针设置为默认值(例如 null),具体取决于您是在调试模式还是发布模式下编译。因此,事情可能会以一种模式运作,但突然间,一切都会在另一种模式下崩溃。

Until you dereference the pointer it's all good, then it's undefined territory.

Some compilers will set pointers to default values (like null) depending if you compile in debug or release mode. So things could work in one mode and suddenly everything falls apart in another.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文