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

可用其他方式完成的转换不应使用 reinterpret_cast

12.20 ID_unsuitableReinterpretCast
目录 › next › previous

reinterpret_cast 将地址强行按另一种类型解释,不考虑转换需要的逻辑,可用 static_cast、dynamic_cast 完成的转换不应使用 reinterpret_cast。

示例:

struct A { int a = 1; };
struct B { int b = 2; };
struct C: A, B {};

int main() {
    C c;
    cout << static_cast<B*>(&c)->b << ' ';
    cout << reinterpret_cast<B*>(&c)->b << '\n';  // Non-compliant, what is output?
}

输出 2 1,如果想将派生类对象的地址 &c 转为基类指针,应使用 static_cast 进行正确的偏移转换,使用 reinterpret_cast 不会进行偏移转换,得到的成员 b 不是真实的成员 b。

相关

ID_voidCast

依据

ISO/IEC 14882:2003 5.2.10(7)-unspecified ISO/IEC 14882:2011 5.2.10(7)-unspecified

参考

C++ Core Guidelines Pro.safety
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.