j4x*_*j4x 5 c++ g++ sizeof visual-c++ constexpr
今天有人请我帮忙做一个用 G++ 编译的 VC++ 项目,我偶然发现了这一行:
static char data[constexpr(sizeof(T))];
Run Code Online (Sandbox Code Playgroud)
(当然,它位于带有名为 的模板参数的模板函数内T)。
我没有 C++ 标准,但根据cppreference:
句法
sizeof( 类型 ) (1)
表达式的大小 (2)
两个版本都是 std::size_t 类型的常量表达式。
sizeof()那么告诉 VC++预期的结果有什么意义呢constexpr?
尝试一下: https: //rextester.com/VIWP36674。
正如预期的那样,在 VC 上有效,但在 G++ 上失败。
另一种尝试选择: https: //godbolt.org/z/DnioLS
适用于 VC 直至 19.10。似乎是在 19.14 修复的,所以我认为这确实是一个怪癖,但即使如此,也一定有人有理由编写这样的代码......
Visual Studio 接受表达式中的无效语法,包括constexpr,consteval和constinit关键字。例如,这个无效程序被最新的MSVC接受:
static_assert( constexpr(sizeof(int)) == sizeof(int) );
static_assert( consteval(sizeof(int)) == sizeof(int) );
static_assert( constinit(sizeof(int)) == sizeof(int) );
Run Code Online (Sandbox Code Playgroud)
演示: https: //gcc.godbolt.org/z/5WqPT74ab