Avoid Casts

C++ Primer 4/e 在Expressions这里还有一个忠告:‘By using a cast, the programmer turns off or dampens normal type-checking (Section 2.3, p.44). We strongly recommend that programmers avoid casts and believe that most well-formed C++ programs can be written without relying on casts.

This advice is particularly important regarding use of reinterpret_casts. Such casts are always hazardous. Similarly, use of const_cast almost always indicates a design flaw. Properly designed systems should not need to cast away const. The other casts, static_cast and dynamic_cast, have their uses but should be needed infrequently. Every time you write a cast, you should think hard about whether you can achieve the same result in a different way. If the cast is unavoidable, errors can be mitigated by limiting the scope in which the cast value is used and by documenting all assumptions about the types involved.’

中文版的是这样说:‘一旦使用强制转型,程式员便是关闭或压抑了正常的型别检验。我们强烈建议程式员避免强制转型,我们也相信,大部分形式良好的C++程式不需依赖强制转型便可写成。

这个忠告在使用reinterpret_casts时特别重要。这种转型总是危险的。类似情况,使用const_cast几乎总是代表某种设计上得缺陷。设计恰当的系统不该需要转掉const。其他转型static_cast和dynamic_cast有其用途但应该不常需要。每次写下强制转型,你应该努力想想是否能以不同的方法达成相同结果。如果强制转型不可避免,可藉着“限制转型后的范围值”以及“将涉及型别的所有相关假设写成技术文件”来尽可能降低错误发生机率。’

转型确实不要常用,而且既然已经宣告了const就不要转来转去了,有这个需要的人真的要好好检讨!