第四次编辑:原始问题标题是:
为什么
constexpr说明符不允许非空std::vector?
正如 @Barry 指出的,这个标题与C++20 constexpr vector and string not working重复。但我的问题描述有所不同:我constexpr vector在constevalfunction而不是正常的运行时 function 或constexprfunction中分配。
据我所知,在编译时计算期间,只允许瞬时分配,正如 @Barry 在链接问题中回答的那样。
我感到困惑的是:对于consteval功能:
constexpr vector作为局部变量,将在编译时释放我在下面的其他编辑回答了这个困惑。
-----------------以下是原问题描述----------
为什么下面的代码不能编译:
consteval int foo() {
constexpr std::vector<int> vec{1};
return vec[0];
}
Run Code Online (Sandbox Code Playgroud)
据我所知,只要分配和释放都发生在编译时,就可以在编译时使用 和std::vector。std::string如果我删除constexpr说明符,该代码将编译。
但是添加constexpr仍然不违反这个规则,对吗?为什么不允许?
使用 gcc 13 编译时出现此错误,但我不明白:
/opt/compiler-explorer/gcc-13.1.0/include/c++/13.1.0/bits/allocator.h:195:52: error:
'std::vector<int>(std::initializer_list<int>{((const int*)(& …Run Code Online (Sandbox Code Playgroud)