开发者

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

开发者 https://www.devze.com 2023-02-24 18:00 出处:网络
Recently I stumbled over code such as this: void foo(const Bar* b) { ... takes_nonconst_param_fn((Bar*)b);

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 t开发者_运维百科his.

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号