Is “sizeof new int;” UB?

  • A+


#include<iostream>  using namespace std;  int main()  {     size_t i = sizeof new int;      cout<<i; } 

In GCC compiler, working fine without any warning or error and printed output 8.

But, in clang compiler, i got following warning:

warning: expression with side effects has no effect in an unevaluated context [-Wunevaluated-expression]     size_t i = sizeof new int; 
  • Which one is true?
  • Is sizeof new int; UB?


The warning doesn't state that it's UB; it merely says that the context of use, namely sizeof, won't trigger the side effects (which in case of new is allocating memory).

[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.

The standard also helpfully explains what that means:

[expr.context] (...) An unevaluated operand is not evaluated.

It's a fine, although a weird way to write sizeof(int*).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: