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

对成员或基类对象的不合理引用

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

对具有 non-trivial 构造函数的对象,在构造函数执行之前引用其非静态成员或基类对象,或者在析构函数执行之后引用其非静态成员或基类对象,会导致未定义的行为。

示例:

struct A {              // Trivial
    int a;
};

struct B: A {           // Non-trivial
    B();
    int b;
};

extern B obj;           // The object is defined later
B* p = &obj;            // OK
int* p1 = &obj.a;       // Undefined, refers to base class member
int* p2 = &obj.b;       // Undefined, refers to member

A* pa = &obj;           // Undefined, upcast to a base class type

extern A trvlObj;       // The object is defined later
int* p3 = &trvlObj.a;   // OK, A is a trivial class

B obj;                  // Define the object
A trvlObj;              // Define the object

依据

ISO/IEC 14882:2003 12.7(1)-undefined ISO/IEC 14882:2011 12.7(1)-undefined
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.