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

    /*
    基类析构函数[是虚函数]:
        指向派生类的基类指针在析构的时候
        [普通指针,shared_ptr,unique_ptr][都会先调用派生类的析构函数,然后再调用基类的析构函数]
     */
    /*
    基类析构函数[不是虚函数]:
        指向派生类的基类指针在析构的时候
        [普通指针,unique_ptr][只会调用基类的析构函数,不会调用派生类的析构函数]
        [shared_ptr][会先调用派生类的析构函数,然后再调用基类的析构函数]
     */
    
    #include <iostream>
    #include <string>
    #include <memory>
    
    class BaseA
    {
        int data;
        std::string msg;
    public:
        BaseA() {
            msg="BaseA message";
        }
    
        /*
        ~BaseA() {
            std::cout<<__FUNCTION__<<std::endl;
        }
         */
        
        virtual ~BaseA() {
            std::cout<<__FUNCTION__<<std::endl;
        }
    
        virtual void show_msg() {
            std::cout<<msg<<std::endl;
        }
    };
    
    class DeriveA:public BaseA
    {
        int data;
        std::string msg;
    public:
        DeriveA() {
            msg="DeriveA message";
        }
    
        ~DeriveA() {
            std::cout<<__FUNCTION__<<std::endl;
        }
    
        
        void show_msg() {
            std::cout<<msg<<std::endl;
        }
    };
    
    void UsePrivateFunc() {
        {
            std::cout<<"ptr BaseA:"<<std::endl;
            BaseA* ptr_BaseA(new DeriveA());
            ptr_BaseA->show_msg();
            delete ptr_BaseA;
        }
        std::cout<<"
    ";
        
        {
            std::cout<<"unique_ptr BaseA:"<<std::endl;
            std::unique_ptr<BaseA> uptr_BaseA(new DeriveA());
            uptr_BaseA->show_msg();
        }
        std::cout<<"
    ";
        
        {
            std::cout<<"shared_ptr BaseA:"<<std::endl;
            std::shared_ptr<BaseA> sptr_BaseA(new DeriveA());
            sptr_BaseA->show_msg();
        }
    }
    
    int main(int argc,char* argv[])
    {
        UsePrivateFunc();
        return 0;
    }
    

    析构函数是虚函数的输出结果:

    析构函数不是虚函数的输出结果:

  • 相关阅读:
    pycharm如何快速替换代码中的字符
    tcp三次握手四次挥手那些事
    Python之异常处理
    Python之单例模式
    ApplicationContext
    ContextLoaderListener作用详解
    DispatcherServlet--Spring的前置控制器作用简介
    web.xml中servlet的配置
    Hibernate各种主键生成策略与配置详解【附1--<generator class="foreign">】
    java.util.ConcurrentModificationException 解决办法(转)
  • 原文地址:https://www.cnblogs.com/smallredness/p/11019451.html
Copyright © 2011-2022 走看看