由于cppcheck cstyleCast样式警告,我试图消除代码库中的所有C风格转换。
将C风格转换为static_cast总是安全的吗?
安全,我的意思是说,有一种情况,旧的C风格的演员工作正常,但static_cast会引发错误或未定义的行为?
type1 a; type2 b = (type2)a; // C style cast type2 b = static_cast<type2>(a); // Is this always a valid replacement for above cast?I am trying to eliminate all C-style casts in a codebase, due to cppcheck cstyleCast style warnings.
Is it always safe to change a C-style cast to a static_cast?
By safe, I mean, is there a situation where the old C-style cast would work fine, but static_cast would raise error or undefined behavior?
type1 a; type2 b = (type2)a; // C style cast type2 b = static_cast<type2>(a); // Is this always a valid replacement for above cast?最满意答案
C风格转换通常是static_cast<>或reinterpret_cast<>与const_cast<> 。 使用static_cast<>替换它可能会导致编译时错误。
我不知道任何运行时错误的情况。
您可以从static_cast<>开始,然后添加(或替换为) const_cast<> ,其中出现编译时错误。 如果在此之后仍然存在编译时错误,则需要reinterpret_cast<> 。 但不要盲目替换 - 这些情况中的一些可能是bug。 例如,如果数据类型是向前声明的但未定义的,则可能需要reinterpret_cast<> ,这会导致未指定的行为(并且如果涉及多重继承,肯定会导致问题)。
寻找这些类型的错误是该练习提高源代码安全性的原因,以及为什么静态代码分析器会标记C风格的演员表。
C-style cast is generally a combo of static_cast<> or reinterpret_cast<> with const_cast<>. There might be compile-time errors from replacing it with just static_cast<>.
I am not aware of any cases for runtime errors.
You could start with static_cast<>, then add (or replace it with) const_cast<> where compile-time errors arise. If after that you still have compile-time errors, reinterpret_cast<> are required. But do not make the replacement blindly - some of these cases may be bugs. E.g., reinterpret_cast<> may be required if a data type is forward declared but not defined, which leads to unspecified behavior (and will definitely cause problems if multiple inheritance is involved).
Finding these kinds of bugs is the reason why this exercise improves safety of the source code, and why a static code analyzer flags C-style casts.
更多推荐
发布评论