在〜Derived()和〜Base()调用之间的对象状态 [英] The state of an object between a call to ~Derived() and ~Base()

查看:85
本文介绍了在〜Derived()和〜Base()调用之间的对象状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在派生类的析构函数执行后,但在基类的执行之前的
时间内,C ++标准对对象状态的保证是什么?析构函数执行? (这是调用派生类的子对象的析构函数的时间。)

What does the C++ standard guarantee about the state of an object in the time after a derived class's destructor executes, but before the base class's destructor executes ? (This is the time when the derived class's subobjects' destructors are being called.)

#include <string>
struct Base;

struct Member {
  Member(Base *b);
  ~Member();
  Base *b_;
};

struct Base {
  virtual void f() {}
  virtual ~Base() {}
};

struct Derived : Base {
  Derived() : m(this) {}
  virtual ~Derived() {}  
  virtual void f() {}
  std::string s; 
  Member m;
};

Member::Member(Base *b) : b_(b) {}
Member::~Member() {
  // At this point, ~Derived has finished -- can we use b_ as a 
  // Derived* object (i.e. call Derived::f or access Derived::s)?
  b_->f();
}

int main() {
  Base *bd = new Derived;
  delete bd;
}

在此示例中,成员对象具有一个指向拥有它的 Derived 对象的指针,并且它尝试以以下方式访问该 Derived 对象:它已被破坏...即使 Derived 的析构函数已经完成。

In this example, a Member object has a pointer to a Derived object that owns it, and it attempts to access that Derived object as it is destructed...even though the destructor for Derived has already finished.

<$ c的哪个版本如果在〜Derived()执行之后但在<$之前执行某个称为虚拟函数的子对象,则会调用$ c> * bd 的虚拟函数。 c $ c>〜Base()执行?进入 * bd 甚至合法吗?

Which version of *bd's virtual functions would be called if some subobject called a virtual function after ~Derived() executes, but before ~Base() executes? Is it even legal to access *bd when it's in that state?

推荐答案

from n3290 [class.cdtor]

from n3290 [class.cdtor]

12.7构造和销毁
1对于具有非平凡构造函数的对象,引用任何非静态成员或构造函数开始执行之前对象的基类会导致未定义的行为。 对于具有非平凡析构函数的对象,在析构函数完成执行后引用该对象的任何非静态成员或基类都会导致未定义的行为。

12.7 Construction and destruction 1 For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior. For an object with a non-trivial destructor, referring to any non-static member or base class of the object after the destructor finishes execution results in undefined behavior.

这篇关于在〜Derived()和〜Base()调用之间的对象状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆