编译器切换在c风格的cast中禁用const_cast sematics? [英] Compiler switch to disable const_cast sematics in c-style casts?
问题描述
最近我偶然发现了这样的代码:
Recently I stumbled over code such as this:
void foo(const Bar* b) {
...
takes_nonconst_param_fn((Bar*)b);
...
显然,开发人员不知道他在做什么,如果编译器没有默默地接受c风格的转换并且至少需要一个适当的 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风格铸造?
So this got me thinking, do any modern compilers have a switch to prevent const_cast
semantics for c-style-casts?
阻止所有出现的c风格的转换是不现实的,这是一个必要的邪恶,允许他们 static _
和 reinterpret _
语义(如果只是对于一些库代码),但我的印象是,合法使用c风格的casts丢弃constness是非常罕见的 C ++ <
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风格的cast中禁用const_cast sematics?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!