以下安全吗?

*(new int);

我得到输出为 0

最佳答案

它是未定义的,因为您正在读取具有不确定值的对象。表达式 new int() 使用零初始化,保证零值,而 new int(不带括号)使用默认初始化,给你一个不确定的值。这实际上等同于说:

int x;              // not initialised
cout << x << '\n';  // undefined value

但是另外,由于您立即取消引用指向您刚刚分配的对象的指针,并且没有将指针存储在任何地方,这构成了内存泄漏。

请注意,这种表达式的存在并不一定会使程序格式错误;这是一个完全有效的程序,因为它在读取对象之前设置了它的值:
int& x = *(new int);  // x is an alias for a nameless new int of undefined value
x = 42;
cout << x << '\n';
delete &x;

关于c++ - 如果取消引用 `new int` 会发生什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25395297/

10-11 22:40
查看更多