Recently I stumbled over code such as this:
void foo(const Bar* b) {
...
takes_nonconst_param_fn((Bar*)b);
...
Obviously, the developer didn't know what he was doing, but if the compiler hadn't silently accepted the c-style-cast and at least required a proper const_cast
, he may have though twice before committing this.
So this got me thinking, do any modern compilers have a switch to prevent const_cast
semantics for c-style-casts?
It's simply not practical to prevent all occurrences of c-style-casts and it's a necessary evil to allow their static_
and reinterpret_
semantics (if only for some library code), but my impression is, that legitimate usage of c-style-casts to cast away constness is very rare in C++ code bases, so maybe it should be possible to disable it altogether?
const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.
If you are careful, you can use const_cast to allow you to retain the const-correctness of your code while still using the library. But you should try to bottleneck those situations to make them as few as possible. tl;dr: const_cast is likely something you should never use.
The whole purpose of const is to prevent you from modifying something, that's why your code generates an error. Adding in const_cast is basically telling the compiler to shut up, that you know what you're doing.
If you cast away the constness of an object that has been explicitly declared as const, and attempt to modify it, the results are undefined. However, if you cast away the constness of an object that has not been explicitly declared as const, you can modify it safely.
GCC has the option -Wcast-qual
to warn when a C-style cast removes a type qualifier. Combined with -Werror
, you can prevent it completely if you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With