我在尝试创建时遇到奇怪的编译器错误constexpr
std::string
and std::vector
对象:
#include <vector>
#include <string>
int main()
{
constexpr std::string cs{ "hello" };
constexpr std::vector cv{ 1, 2, 3 };
return 0;
}
编译器抱怨“表达式必须具有常量值”:
我错过了什么吗?我正在使用最新的 Microsoft Visual Studio 2019 版本:16.11.4,以及参考(https://en.cppreference.com/w/cpp/compiler_support https://en.cppreference.com/w/cpp/compiler_support)指出constexpr
此编译器版本支持字符串和向量:
我也尝试过constexpr std::array
,这确实有效。该问题是否与向量相关的动态内存分配有关?
您的程序实际上格式不正确,尽管该错误可能很难理解。constexpr
C++20 中的分配支持是有限的 - 你只能有短暂的分配。也就是说,分配必须在持续评估结束时完全解除分配。
所以你不能这样写:
int main() {
constexpr std::vector<int> v = {1, 2, 3};
}
Because v
的分配仍然存在 - 它是非暂时性的。这就是错误告诉您的内容:
<source>(6): error C2131: expression did not evaluate to a constant
<source>(6): note: (sub-)object points to memory which was heap allocated during constant evaluation
v
不能是常量,因为它仍然保留堆分配,并且不允许这样做。
But you can write this https://godbolt.org/z/P7x4Y1x6Y:
constexpr int f() {
std::vector<int> v = {1, 2, 3};
return v.size();
}
static_assert(f() == 3);
Here, v
的分配是暂时的 - 内存被释放时f()
返回。但我们仍然可以使用std::vector
during constexpr
time.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)