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就不要轉來轉去了,有這個需要的人真的要好好檢討!

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *