代码:
#include<iostream>
using namespace std;
int main()
{
size_t i = sizeof new int;
cout<<i;
}
在 GCC 编译器中,工作正常,没有任何警告或错误,并打印输出 8
.
但是,在 clang 编译器中,我收到了以下警告:
warning: expression with side effects has no effect in an unevaluated context [-Wunevaluated-expression]
size_t i = sizeof new int;
- 哪一个是真的?
sizeof new int;
是未定义的行为吗?
最佳答案
警告没有说明它是 UB;它只是说使用的上下文,即 sizeof
,不会触发副作用(在 new
的情况下是分配内存)。
[expr.sizeof] The sizeof operator yields the number of bytes occupied by a non-potentially-overlapping object of the type of its operand. The operand is either an expression, which is an unevaluated operand ([expr.prop]), or a parenthesized type-id.
该标准还有助于解释这意味着什么:
[expr.context] (...) An unevaluated operand is not evaluated.
这很好,虽然写 sizeof(int*)
的方式很奇怪。
关于c++ - "sizeof new int;"是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52624526/