behavior of const_cast in C++ [duplicate]

As-written the way you’re doing this is undefined behavior. If you wanted to see the effects of const_cast<> in a defined manner:

int a = 5;                  // note: not const. regular object.
const int& cref = a;        // const-reference to same object.
cref = 7;                   // illegal. cref is a const reference.
const_cast<int&>(cref) = 7; // legal. the original object a is not const.

The only reason this is defined behavior is due to the non-const nature of the original variable, a. You cannot take an outright-const object and simply cast away the const-ness, which is what your posted code did. (at least as it has been explained to me on several occasions).

Leave a Comment