6

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Martin Ba
  • 37,187
  • 33
  • 183
  • 337
  • Does it make any difference if you declare foo as 'void foo(const Bar* b) const'? – James Apr 13 '11 at 14:24
  • 2
    @James: why do you expect that to affect how explicit casts work? If `foo` is a member function, then that would make the object members `const` within the function; if not, then that would be an error. – Mike Seymour Apr 13 '11 at 14:45
  • 1
    Actually I wish I could disable all but their `static_cast` form. – edA-qa mort-ora-y Apr 13 '11 at 14:51

1 Answers1

7

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644