简体   繁体   中英

Is “sizeof new int;” undefined behavior?

code:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM