澄清一下,以下程序格式是否正确?
#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++ 语言版本。
关于c++ - 从一个新的位置访问一个静态 constexpr 成员是一个常量表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68248117/