问题描述
澄清一下,以下程序是否格式良好?
#include <new>
char foo[32];
struct bar {
static constexpr int foobar = 42;
};
int main()
{
auto p = new (foo) bar();
static_assert(p->foobar == 42);
}
gcc 和 msvc 接受,但 clang 因错误而拒绝
read of non-constexpr variable 'p' is not allowed in a constant expression
,谁是对的?
解决方法
如果您将其更改为:
auto constexpr p = new (foo) bar();
然后clang错误信息变得更清晰:
<source>:12:24: error: constexpr variable 'p' must be initialized by a constant expression
auto constexpr p = new (foo) bar();
^ ~~~~~~~~~~~~~~~
<source>:12:28: note: dynamic memory allocation is not permitted in constant expressions until C++20
auto constexpr p = new (foo) bar();
^
所以答案取决于 C++ 语言版本。