Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler switch to disable const_cast semantics in c-style casts?

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_castsemantics 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?

like image 562
Martin Ba Avatar asked Apr 13 '11 14:04

Martin Ba


People also ask

What is const_cast in C?

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.

Should I use const_cast?

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.

Why does const cast exist?

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.

Is const cast Safe?

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.


1 Answers

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.

like image 179
Mike Seymour Avatar answered Sep 24 '22 02:09

Mike Seymour