从一个新的位置访问一个静态 constexpr 成员是一个常量表达式吗?

时间:2021-07-04 19:24:46

标签: c++ language-lawyer static-members placement-new constant-expression

澄清一下,以下程序是否格式良好?

#include <new>
char foo[32];
struct bar {
        static constexpr int foobar = 42;
};

int main() 
{
        auto p = new (foo) bar();
        static_assert(p->foobar == 42);
}

gccmsvc 接受,但 clang 因错误而拒绝 read of non-constexpr variable 'p' is not allowed in a constant expression,谁是对的?

1 个答案:

答案 0 :(得分:0)

如果您将其更改为:

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++ 语言版本。

相关问题