gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:01:56 25 4
gpt4 key购买 nike

澄清一下,以下程序格式是否正确?

#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 ,谁是对的?

最佳答案

如果将其更改为:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com