support - gcc 4.4.7 c++11

Is “sizeof new int;” undefined behavior? (2)

new operator returns pointer to the allocated memory. new int will return a pointer, therefore sizeof new int; will return size of a pointer. This is a valid code and there is no undefined behaviour here.

Warning is legit and only warns about the effect of side-effect on the operand and that's because operands of sizeof is not evaluated.

For example:

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



using namespace std;

int main() 
    size_t i = sizeof new int;


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

But, in clang compiler, I got the 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; undefined behavior?

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*).