为什么我不能 push_back 到 const 元素的向量?

Why can't I push_back to a vector of const elements?

push_back对非常量元素的向量按预期工作:

std::vector<int> foo;
int bar = 0;
foo.push_back(bar);

但是为什么下面的不可以呢?

std::vector<const int> foo;
const int bar = 0;
foo.push_back(bar);

更准确地说,为什么可以创建 foo 对象但不能对其调用 push_back

根据 this answer(来自一位 C++11 设计者的评论),标准不允许 std::vector<const T>

答案表明可以提供一个自定义分配器,它允许带有该分配器的向量保存 const 对象。

你最好不要尝试这样做。