具有未初始化指针的类是否具有未定义的行为?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
类内未初始化的指针与独立的未初始化指针没有任何区别。只要您不以任何危险的方式使用指针,就没有问题。
请记住,使用未初始化指针的“危险方式”包括仅仅尝试读取其值(无需取消引用)。如果您在为指针分配有效值之前使用这些隐式成员函数,则类中存在的隐式编译器提供的复制构造函数和复制赋值运算符可能会执行此类尝试。
事实上,如果我没记错的话,这个问题是标准化委员会层面上的一些讨论的问题。隐式生成的成员函数是否允许绊倒可能存在于类的非初始化成员中的陷阱表示?我不记得判决是什么了。 (或者也许我在 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?)
是的,没关系。指针本身存在,只是它的值未知,因此取消引用它是不安全的。有一个未初始化的变量是完全可以的,指针也没有什么不同
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
是的,这与带有单个未初始化指针的 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).在取消引用指针之前一切都很好,然后它就是未定义的区域。
某些编译器会将指针设置为默认值(例如 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.