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

在分配空间后,生命周期开始前,或在生命周期结束后,回收空间前,通过指针访问对象

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

在对象的生命周期之外,通过指针进行如下操作会导致未定义的行为:

  • 访问非静态成员函数
  • 将指针转为基类指针
  • 用 static_cast 转换指针(转为 void*、char*、unsigned char* 等情况除外)
  • 用 dynamic_cast 转换指针

示例:

struct T {
    T();
   ~T();
    void fun();
};

T* p = (T*)malloc(sizeof(T));
p->fun();   // Undefined behavior, the lifetime has not yet started

new (p) T();
p->fun();   // Well-defined

p->~T();
p->fun();   // Undefined behavior, the lifetime has ended

free(p);

依据

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