zoukankan      html  css  js  c++  java
  • c++ 虚拟析构函数

      

        通过基类指针删除派生类对象,基类又没有虚析构函数,结果不可确定。(派生类的析构函数没有被调用,派生类的对象没有被回收)。

     如下是没有定义虚拟的析构函数。

    #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( ) 请按任意键继续. . .


     

  • 相关阅读:
    Sublime text 3支持utf-8
    ubuntu17.10 安装firefox的flash
    opencv mat裁剪
    Ubuntu寻找某某库
    Ubuntu的 g++ gcc版本升降级
    Autotools知识点
    Counted(内存管理机制)
    operator new和operator delete
    STL学习笔记:空间配置器allocator
    function call操作符(operator()) 仿函数(functor)
  • 原文地址:https://www.cnblogs.com/youxin/p/2582021.html
Copyright © 2011-2022 走看看