将C风格转换为static

编程入门 行业动态 更新时间:2024-10-26 19:37:25
将C风格转换为static_cast总是安全的吗?(Is it always safe to change a C-style cast to a static_cast?)

由于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.

更多推荐

本文发布于:2023-08-06 18:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1453885.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   风格   static

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!