According to §7.1.5.1/4:
Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.
So my question becomes: when is an object a const object?
In particular, is a const member in a non-const object considered a const object?
class Foo {
const Bar bar;
void replaceBar(Bar bar2) {
*(const_cast<Bar *>&bar) = bar2; // Undefined behavior?
}
}
This comes up because I have an immutable class (all fields are const), but I want to have a move constructor, which technically modifies the value passed in. I'm ok with "cheating" in that case, since it doesn't break logical constness.
Let us make this a full example:
now, let us break the world.
the above can and probably should output 3, because a
constobjectBarwas created withx=3. The compiler can, and should, assume that theconstobject will be unchanged throughout its lifetime.Let's break the world more:
now the same game can result in the compiler deleting something twice.
and the compiler will delete
p1once withinreplaceBar, and should delete it also at the end ofmain. It can do this, because you guaranteed thatf.bar.xwould remain unchanged (const) until the end of its scope, then you violated that promise inreplaceBar.Now, this is just things the compiler has reason to do: the compiler can literally do anything once you have modified an object that was declared
const, as you have invoked undefined behavior. Nasal demons, time travel -- anything is up for grabs.Compilers use the fact that some behavior is undefined (aka, not allowed) to optimize.