When const is not const: const_cast

I’m sure most C++ developers will be familiar with const_cast<>. If you aren’t, it’s a way of removing or adding the const or volatile modifiers to an object.

Example

const int my_var = 10;
int * nonconst_ptr = const_cast< int >( &my_var ); // *gasp* non-const pointer to it!

It’s an ugly, ugly thing! const is undoubtedly there for a reason! However, I did see a (reasonable) case for its use today – in overloaded operators. You might have a const and non-const version of the same operator. The non-const may well be for internal use in the class. Works quite well without having two functions copy the same code which essentially does the same thing, only one returns const and the other not.

Be that as it may, the question crossed my mind – if I took the const off a variable, could I modify it? Could I, in my previous example above, change my_var using:

*nonconst_ptr = 5;

Answer is no. That operation is undefined. You still can’t modify a const value by typecasting it away. Indeed, under GCC it does not change the original variable. I guess it would make sense though given compilers can, and do treat const values as special cases. Various optimizations apply. Also, it would break things considerably if const were not always const.

So what then of my previous comments that there was a use for it? Well in the above example, the original my_var is const. And as such, its const‘ness is guarenteed. However, if the original is _not_ const, then you may modify it:

int my_var = 10; // note no longer const
const int * const_ptr = &my_var; // we make a const pointer to the non-const my_var
int * nonconst_ptr = const_cast< int >( const_ptr );

*nonconst_ptr = 5; // this will change it to 5


About this entry