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

std::vector<const int>是否属于未定义行为?附相关技术疑问

关于std::vector的两个疑问

最近我在研究C++容器的相关特性,看了相关讨论后写了下面这段测试代码:

#include <iostream>
#include <vector>
int main() {
    const int x = 5;
    // x = 200; 当然不可行。
    std::vector<const int> xVector = { 5 };
    xVector[0] = 200;
    std::cout << xVector[0]; // 200,不出意外。
}

这段代码能在Visual Studio 2017里正常编译运行,输出结果是200,但我心里一直打鼓:

  • 这种直接修改std::vector<const int>元素的行为,是不是属于未定义行为(UB)?
  • 从技术层面来讲,为什么std::vector<const int>并非是一个只能存放不可修改int的容器呢?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:37:27