You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何在std::vector上使用constexpr说明符无法正常工作?

constexpr std::vector 非空初始化的编译错误分析
  • 目前在主流编译器中,非空初始化constexpr std::vector会触发编译错误。此前因本地MSVC版本较新,空初始化std::vector时会报错,但在线编译平台未触发该错误,引发了混淆。

示例代码

#include <vector>

constexpr std::size_t f() {
    constexpr std::vector<int> v{ 1 };
    return 1;
}

int main() {
    constexpr auto a = f();
}

MSVC 报错信息(使用/std:c++latest编译选项)

ConsoleApplication9.cpp(12,24): error C2131: 表达式未计算为常量
ConsoleApplication9.cpp(12,24): 消息:(子)对象指向常量求值期间堆分配的内存

GCC 报错信息(翻译后)

错误:std::vector(std::initializer_list{((const int*)(& const int [1]{1})), 1}, std::allocator()) 不是常量表达式,因为它引用了operator new的结果
195 | return static_cast<_Tp*>(::operator new(__n));
| ~~~~~~~~~~^

内容的提问来源于stack exchange,提问作者Tom Huntington

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 11:57:04