c++ 虚拟析构函数
2012-07-09 00:01
246 查看
通过基类指针删除派生类对象,基类又没有虚析构函数,结果不可确定。(派生类的析构函数没有被调用,派生类的对象没有被回收)。如下是没有定义虚拟的析构函数。
#include <iostream> using namespace std; class Base { public: Base( void ) { cout << "Base::Base( )" << endl; } ~Base( void ) //基类没有虚析构函数时 { cout << "Base::~Base( )" << endl; } }; class Derived : public Base { public: Derived( void ) { m_pData = new int; cout << "Derived::Derived( )" << endl; } ~Derived( void ) { delete m_pData; m_pData = NULL; cout << "Derived::~Derived( )" << endl; } private: int* m_pData; }; int main( void ) { Derived* pD = new Derived; Base* pB = pD; //通过基类的指针去删除派生类的对象,而基类又没有虚析构函数时,结果将是不可确定的。 //(此处是派生类的析构函数没有被调用。) delete pB; pB = NULL; system( "PAUSE" ); return EXIT_SUCCESS; }
/*-------派生类的析构函数没有被调用,当然派生类的对象没有被回收 Base::Base( ) Derived::Derived( ) Base::~Base( ) 请按任意键继续. . . 如果加上virtual ,就会输出:
/*-------派生类的析构函数没有被调用,当然派生类的对象没有被回收 Base::Base( ) Derived::Derived( ) Derived::~Derived() Base::~Base( ) 请按任意键继续. . .
相关文章推荐
- C++箴言:多态基类中将析构函数声明为虚拟zz
- 什么时候需要C++虚拟析构函数
- C++虚拟析构函数
- 重温C++之虚拟析构函数
- C++中析构函数为什么有时候写成虚拟的
- C++ 虚函数、多态性的演示 -- 虚拟析构函数
- [C++] C++中的虚拟析构函数有什么作用?
- C++基础知识---构造函数 & 析构函数 & 虚拟析构函数
- [C++] C++中的虚拟析构函数有什么作用?
- C++ 虚拟析构函数
- C++ 虚函数、多态、为什么需要虚拟析构函数
- C++析构函数的自动调用(析构函数必须是虚拟的,这样删除父类指针指向的子类对象,才能同时调用两者的析构函数,否则就没有机会调用子类析构函数)
- C++箴言:多态基类中将析构函数声明为虚拟
- C++之虚拟析构函数
- c++对象模型-虚拟析构函数
- Effective C++ Item 09-绝不在构造函数和析构函数中调用virtual函数
- c++ 析构函数调用解析
- c++中的类(构造函数,析构函数的执行顺序)
- C++ 析构函数
- C++中虚析构函数的作用