为什么 vector::erase 不能在带有 const 的 class 元素上工作

Why vector::erase can't work on class element with const

我试图擦除存储包含 const 成员的 class 的向量元素,但我失败了并出现错误。

当我去掉常量修饰符后,程序编译正常。

class C
{
public:
    const int i;
    C(int i = 1):i(i){};
};


int main()
{
    vector<C> v;
    C c;
    v.push_back(c);
    v.erase(v.begin());
    return 0;
}

error C2280: 'C &C::operator =(const C &)': attempting to reference a deleted function
m.cpp(151): note: compiler has generated 'C::operator =' here
m.cpp(151): note: 'C &C::operator =(const C &)': function was implicitly deleted because 'C' has a data member 'C::i' of const-qualified non-class type
m.cpp(146): note: see declaration of 'C::i'

矢量上的某些操作需要复制元素或 move-assignable [ref]。

在这种情况下,您会看到 .erase 函数的实现无法编译,因为它需要知道如何在容器 [ref] 中随机排列元素(即使您的特定示例只会导致空向量)。

当你创建一个成员时 const,你就阻止了它。

你不能拥有那个 const