☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

在 C++ 代码中禁用 C 风格类型转换

12.22 ID_forbidCStyleCast
目录 › next › previous

C 风格类型转换易造成数据丢失或逻辑错误,在 C++ 代码中应使用 static_cast、dynamic_cast 等方法代替 C 风格类型转换。

示例:

class A { .... };
class B { .... };

void foo(A* a) {
    B* b = (B*)a;  // Non-compliant, an error value with no logical meaning
    ....
}

void bar(A* a) {
    B* b = dynamic_cast<B*>(a);  // Compliant, prevent errors at compile-time
    ....
}

例中 A 和 B 是两种不相关的类型,用 C 语言的转换方式是可以转换成功的,但并没有逻辑意义,在 C++ 代码中应使用 static_cast 或 dynamic_cast 等方法在编译时或运行时保障转换的有效性。

参考

C++ Core Guidelines ES.49 MISRA C++ 2008 5-2-4
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.