当成员析构函数运行时,class 具有什么类型的虚函数?

What type for virtual function does a class have when a member destructor runs?

我遇到这种情况:

#include <iostream>

struct B { virtual void f() { std::cout << "base"; } };

struct A {
  ~A() {
      b->f();
  }

  B *b;
};


struct Bd : B { 
  Bd():a{this}{ }
  ~Bd() { }
  virtual void f() { std::cout << "derived"; } 

  A a;
};

int main() {
  Bd d;
}

这能保证打印出"derived"吗?

我现在没时间查,但规则是,对析构函数为 运行ning 的对象的虚拟调用会转到 class,其析构函数当前为 运行宁。所以在Bd的析构函数中,a运行的析构函数中,b->f()调用Bd::f.

如果 aB 的成员而不是 Bd,调用将转到 B::f,因为 a 的析构函数将运行 来自 B 的析构函数。

如果您更喜欢考虑机制(我通常不考虑),请考虑 vtable;在进入析构函数时,代码将 vtable 指针设置为指向属于 运行ning.

析构函数的 vtable

[class.cdtor]/4:

Member functions, including virtual functions ([class.virtual]), can be called during construction or destruction ([class.base.init]). When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class's non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor's or destructor's class and not one overriding it in a more-derived class.

"The class" 这里的问题是 Bd,因此它应该在 Bd 中调用 f() 的最终覆盖程序,并打印 derived.