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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With