• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
看看这个是有什么用
那这个呢
博客园    首页    新随笔       管理    订阅  订阅
析构函数virtual 与non-virtual

http://www.cppblog.com/aaxron/archive/2010/12/23/137293.html
一旦使用的继承机制, 如果基类没有设置为虚函数, 那么子类的析构函数很可能不会调用.
为什么是可能而不是一定呢?
因为是只会在指针的场景;

class Base
{
public:
    Base(){
        cout<<"Base Construcing"<<endl;
    }

    ~Base(){
        cout<<"Base Destrucing"<<endl;
    }

};

class Derived : public Base
{
public:
    Derived(){
        cout<<"Derived Constructing"<<endl;
    }

    ~Derived(){
        cout<<"Derived Destructing"<<endl;
    }
};

int main() {
    Base *base = new Derived;
    delete base;

cout<< "*************分割线*************"<<endl;
    Derived Derived;
    return 0;
}

下面是输出

Base Construcing
Derived Constructing
Base Destrucing
*************分割线*************
Base Construcing
Derived Constructing
Derived Destructing
Base Destrucing
  • 可以看出, 当使用父类指针的时候, 如果虚析构函数不具有多态性(virtual), 那么,Base*就只会调用Base类的析构函数,而不会去寻找子类的析构函数.
  • 也不能把Base* 改成Derived指针,因为Derived指针有一天也可能变成其他类型的父类
posted on 2019-11-19 21:15  明月入怀  阅读(200)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3