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

用 static_cast 将基类指针转为派生类指针,基类为虚基类,或指向的实际对象并非派生类对象

C++-Undefined-Behavior-33
目录 › next › previous

示例:

struct A {};
struct B: A {};
struct C: virtual B {};

A a;
C c;
A* pa = &a;
A* pc = &c;

static_cast<B*>(pa);    // Undefined behavior
static_cast<C*>(pc);    // Undefined behavior

例中 pa 指向基类对象,将其转为派生类指针会导致未定义的行为,A 和 B 是 C 的虚基类,需要运行时数据体现虚基类对象和派生类对象的空间关系,static_cast 不考虑与运行时相关的转换逻辑,无法正确转换。

依据

ISO/IEC 14882:2003 5.2.9(8)-undefined ISO/IEC 14882:2011 5.2.9(11)-undefined

规则

ID_downCast
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.