C++ standard says that modifying an object originally declared const is undefined behavior. But then how do constructors and destructors operate?
Here's a way that ignoring the standard could lead to incorrect behavior. Consider a situation like this:
class Value
{
int value;
public:
value(int initial_value = 0)
: value(initial_value)
{
}
void set(int new_value)
{
value = new_value;
}
int get() const
{
return value;
}
}
void cheat(const Value &v);
int doit()
{
const Value v(5);
cheat(v);
return v.get();
}
If optimized, the compiler knows that v is const so could replace the call to v.get() with 5.
But let's say in a different translation unit, you've defined cheat() like this:
void cheat(const Value &cv)
{
Value &v = const_cast(cv);
v.set(v.get() + 2);
}
So while on most platforms this will run, the behavior could change depending on what the optimizer does.