C++ standard says that modifying an object originally declared const is undefined behavior. But then how do constructors and destructors operate?
class Class {
public:
Class() { Change(); }
~Class() { Change(); }
void Change() { data = 0; }
private:
int data;
};
//later:
const Class object;
//object.Change(); - won't compile
const_cast<Class&>( object ).Change();// compiles, but it's undefined behavior
I mean here the constructor and destructor do exactly the same thing as the calling code, but they are allowed to change the object and the caller is not allowed – he runs into undefined behavior.
How is it supposed to work under an implementation and according to the standard?
The standard explicitly allows constructors and destructors to deal with
constobjects. from 12.1/4 “Constructors”:And 12.4/2 “Destructors”:
As background, Stroustrup says in “Design and Evolution of C++” (13.3.2 Refinement of the Defintion of
const):