"sizeof new int;" 是未定义的行为吗?

Is "sizeof new int;" undefined behavior?

代码:

#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;

警告并没有说明它是 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*)

new 运算符 returns 指向已分配内存的指针。 new int 将 return 一个指针,因此 sizeof new int; 将 return 一个指针的大小。这是一个有效的代码,这里没有 未定义的行为

警告是合法的,只警告操作数的副作用的影响,这是因为 sizeof 的操作数未被评估。

例如:

int i = 1;
std::cout << i << '\n';     // Prints 1
size_t size = sizeof(i++);  // i++ will not be evaluated
std::cout << i << '\n';     // Prints 1