如果取消引用new new int会发生什么? [英] What happens if you dereference `new int`?
问题描述
以下安全吗?
*(new int);
我得到的输出为0
.
推荐答案
它是未定义的,因为您正在读取具有不确定值的对象.表达式new int()
使用零初始化,保证零值,而new int
(不带括号)使用默认初始化,为您提供不确定的值.这实际上与说:
It’s undefined because you’re reading an object with an indeterminate value. The expression new int()
uses zero-initialisation, guaranteeing a zero value, while new int
(without parentheses) uses default-initialisation, giving you an indeterminate value. This is effectively the same as saying:
int x; // not initialised
cout << x << '\n'; // undefined value
但是,此外,由于您将立即将指针重新引用到刚刚分配的对象,并且不将指针存储在任何地方,因此会造成内存泄漏.
But in addition, since you are immediately dereferencing the pointer to the object you just allocated, and do not store the pointer anywhere, this constitutes a memory leak.
请注意,此类表达式的存在并不一定会使程序格式错误;这是一个非常有效的程序,因为它会在读取对象之前设置对象的值:
Note that the presence of such an expression does not necessarily make a program ill-formed; this is a perfectly valid program, because it sets the value of the object before reading it:
int& x = *(new int); // x is an alias for a nameless new int of undefined value
x = 42;
cout << x << '\n';
delete &x;
这篇关于如果取消引用new new int会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!