Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdvector

I tried to erase the element of the vector that stores the class containing the const member, but I failed and got an error.

When I remove the constant modifier, the program compiles normally.

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'
like image 249
nullptr Avatar asked Dec 29 '25 14:12

nullptr


1 Answers

Certain operations on a vector require the elements to be copy- or move-assignable [ref].

In this case, you're seeing the implementation of the .erase function fail to compile because it needs to know how to shuffle elements around in the container [ref] (even though your particular example would merely have resulted in an empty vector).

When you make a member const, you prevent that.

You can't have that const.

like image 89
Lightness Races in Orbit Avatar answered Jan 01 '26 04:01

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!