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

标签 c++ c++11 g++ sizeof clang++

代码:

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

相关文章:

C++ 如何每 10 秒检查一次时间?

c++ - 修改函数中二维引用数组的值

c++ - 为什么 C++ 没有反射?

c++ - 在集合上调用成员方法

c++11 - 是不是Ubuntu 12.04自带的GNU编译器不兼容C++ 11?

c++ - GCC - 包含编译标志的宏

c++ - 这个 noexcept 声明有效吗?

c++ - DirectX:动态顶点声明

当涉及 std::function 或 lambda 函数时,C++11 不推断类型

C++11 可变参数模板函数调用转发