C++ 隐式转换原语的警告或错误 [英] Warnings or errors for C++ implicit conversion of primitives

查看:73
本文介绍了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());
}

问题

  1. b 中,a 的返回类型被默默地转换为 bool.
  2. c 中,从 b 返回的值被静默提升为 int64_t.
  1. In b, the return type of a is silently cast to bool.
  2. In c, the value returned from b is silently promoted to int64_t.

问题

我如何才能收到原始类型之间隐式转换的警告或错误?

  1. -Wconversion 的使用似乎只选择了几个与上述示例无关的任意转换.
  2. BOOST_STRONG_TYPEDEF 不是一个选项(我的类型需要是 POD,因为它们用于磁盘结构).
  3. C 也很有趣,但是这个问题与 C++ 代码库有关.
  1. The use of -Wconversion seems to only pick up several arbitrary conversions unrelated to the example above.
  2. BOOST_STRONG_TYPEDEF is not an option (my types need to be PODs, as they're used in disk structures).
  3. C is also of interest, however this problem pertains to a C++ code base.

推荐答案

C++ 编程语言,第 3 版中,附录 C.6,即隐式类型转换",Bjarne Stroustrup 将转换分类为 promotionsconversions:第一个保留值"(即您的情况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.

这篇关于C++ 隐式转换原语的警告或错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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