C++ 隐式转换原语的警告或错误
我对一些 C++ 代码进行了一些重度重构,并发现了许多由我不知道的隐式转换引起的错误.
I've done some heavy refactoring of some C++ code, and discovered numerous bugs arising from implicit conversions that I'm not aware of.
struct A *a();
bool b() {
return a();
}
void c() {
int64_t const d(b());
}
问题
- 在
b
中,a
的返回类型被默默地转换为bool
. - 在
c
中,从b
返回的值被静默提升为int64_t
.
- In
b
, the return type ofa
is silently cast tobool
. - In
c
, the value returned fromb
is silently promoted toint64_t
.
问题
我如何才能收到原始类型之间隐式转换的警告或错误?
-Wconversion
的使用似乎只选择了几个与上述示例无关的任意转换.BOOST_STRONG_TYPEDEF
不是一个选项(我的类型需要是 POD,因为它们用于磁盘结构).- C 也很有趣,但是这个问题与 C++ 代码库有关.
- The use of
-Wconversion
seems to only pick up several arbitrary conversions unrelated to the example above. BOOST_STRONG_TYPEDEF
is not an option (my types need to be PODs, as they're used in disk structures).- C is also of interest, however this problem pertains to a C++ code base.
推荐答案
在 C++ 编程语言,第 3 版中,附录 C.6,即隐式类型转换",Bjarne Stroustrup 将转换分类为 promotions 和 conversions:第一个保留值"(即您的情况2),第二个没有(情况1).
In the C++ programming language, 3rd edition, appendix C.6, namely "Implicit Type Conversion", Bjarne Stroustrup classifies conversions as promotions and conversions: the first ones "preserve values" (that's your case 2), the second ones doesn't (case 1).
关于转换,他说基本类型可以通过多种方式相互转换.在我看来,允许进行太多转换."和编译器可以警告许多有问题的转换.幸运的是,许多编译器实际上会这样做."
About conversions, he says that "The fundamental types can be converted into each other in a bewildering number of ways. In my opinion, too many conversions are allowed." and "A compiler can warn about many questionable conversions. Fortunately, many compilers actually do."
促销是安全的,似乎编译器不应该对他们发出警告.
promotions on the other side are safe, and it seems like a compiler is not supposed to give a warning for them.
编译器警告通常不是强制性的.通常在 C++ 草案和最终 ANSI 文档 中报告实施者应该发出警告",其中建议:如果需要,您可以自己查看以获取更多信息.
Compiler warnings are usually not mandatory. Usually in the C++ drafts and final ANSI documents it is reported that "implementers should issue a warning" where suggested: you can check it yourself for further information if needed.
已添加了 C++11 注释:
EDITED: added C++11 note:
在C++编程语言,第4版中,已经报道了第3版的附录并再次扩展为第 10.5 节隐式类型转换".
In The C++ programming language, 4th edition, the appendix of the 3rd edition has been reported and extended as section 10.5, "Implicit Type Conversion" again.
与之前的考虑相同,C++11 更精确地定义了缩小转换"并添加了 {}-initializer notation (6.3.5),截断会导致编译错误.
Being the previous considerations the same, C++11 more precisely define "narrowing conversions" and adds up the {}-initializer notation (6.3.5), with which truncations lead to a compilation error.
相关文章