Say we have a class like this:
class A {
public:
A(int aa)
: a(aa) {
}
const int a;
};
with a
being a public property. If I don't want anyone to mess around and change it, I must make it const
, fair enough.
What I don't understand why I can't manipulate such class in a container? The simplest case is replace:
std::vector<A> v;
v.push_back(A(10)); // QVector::append() fails even here
v[0] = A(20); // no-go even for plain vector
Sure I know the technical background behind this operation (basically just overwriting memory belonging to the old instance) but my question is then how I'm supposed to manipulate such container class?
Say I want to replace every second A
instance with a result from some other operation. Do I have to create new container every time?
To be honest, this discovery has caught be surprise, I've always assumed that const variables are local to the given class, i.e. they have no external side effects. Copy constructor is no help here (writing to const variable) so I don't know, maybe one of the new C++11 move ones would help here somehow?
EDIT:
You're right guys, I've been fooled by programming in Java too much. However, it still feels a little bit inconsistent. So I can't overwrite the content of my container, ok. But I can delete, swap, move it without a problem?
` where `S` is a `struct` with a `readonly` field still works (even direct assignment). I wondered why and it appears the tradeoff made was that `readonly` isn't really enforced on structs there. That is, an assignment will modify the memory directly, despite the `readonly`.– chris Feb 07 '17 at 05:06