编译器开关禁用c样式转换中的const_cast语义? [英] Compiler switch to disable const_cast semantics in c-style casts?

查看:100
本文介绍了编译器开关禁用c样式转换中的const_cast语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我偶然发现了这样的代码:

Recently I stumbled over code such as this:

void foo(const Bar* b) {
  ...
  takes_nonconst_param_fn((Bar*)b);
  ...

显然,开发人员不知道他在做什么,但是如果编译器没有默默地接受c-style-cast,并且至少需要一个正确的 const_cast ,那么在提交此代码之前,他可能会有两次。

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.

所以这让我开始思考,是否有任何现代编译器可以切换以防止 const_cast 语义用于c-style-cast?

So this got me thinking, do any modern compilers have a switch to prevent const_castsemantics for c-style-casts?

防止所有c样式转换的发生根本不切实际,而允许它们的 static _ reinterpret _ 语义(如果仅用于某些库代码),但是我的印象是,在 C ++中,很少使用c-style-cast来消除常量性。

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具有选项 -Wcast-qual 会在C样式强制转换删除类型限定符时发出警告。结合 -Werror ,可以完全阻止它。

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.

这篇关于编译器开关禁用c样式转换中的const_cast语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆