为什么vector :: erase无法在具有const的类元素上工作

nul*_*ptr 0 c++ stdvector

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

当我删除常量修饰符时,程序将正常编译。

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'
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 6

向量上的某些运算要求元素是可复制或可移动分配的[ ref ]。

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

当您成为会员时const,您可以避免这种情况。

你不能拥有那个const

  • @SombreroChicken没说太多 (2认同)