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

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

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

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

  • 进行 lvalue-to-rvalue 转换
  • 访问非静态成员函数
  • 向基类引用转换
  • 用 static_cast 转换 glvalue(转为 char& 或 unsigned char& 等情况除外)
  • 用 dynamic_cast 转换 glvalue
  • 将 typeid 作用于 glvalue

示例:

struct B { void foo(); };
struct D: B { .... };

void B::foo() {
    new (this) D;    // Ends the lifetime of *this
}

void bar(B& b) {
    b.foo();
    if (typeid(b) == ....) {   // Undefined behavior
        ....
    }
}

例中 b.foo 执行后 b 的生命周期结束,之后再对 b 的访问会导致未定义的行为。

依据

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