在析构期间,有一些我们可能不希望马上发生的情况。
如果正在一个普通的成员函数中,并且调用一个虚函数,则会使用晚捆绑机制
来调用这个函数
而对于析构函数,这样不行,不论是虚的还是非虚的
在析构函数中,只有成员函数的 本地 版本被调用,虚机制被忽略
//: C15:VirtualsInDestructors.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Virtual calls inside destructors
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() {
cout << "Base1()\n";
f();
}
virtual void f() { cout << "Base::f()\n"; }
};
class Derived : public Base {
public:
~Derived() { cout << "~Derived()\n"; }
void f() { cout << "Derived::f()\n"; }
};
int main() {
Base* bp = new Derived; // Upcast
delete bp;
getchar();
} ///:~
在析构函数的调用中,Derived::f()没有被调用,即使f()是一个虚函数
假设在析构函数中使用虚机制,那么调用下面这样的虚函数是可能的:这个
函数是在继承层次中比当前的析构函数“更靠外的”
输出
~Derived()
Base1()
Base::f()