℡Wang Yan 2009-01-20 12:58 采纳率: 100%
浏览 434
已采纳

什么时候使用虚销毁函数?

I have a solid understanding of most OO theory but the one thing that confuses me a lot is virtual destructors.

I thought that the destructor always gets called no matter what and for every object in the chain.

When are you meant to make them virtual and why?

转载于:https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors

  • 写回答

15条回答 默认 最新

  • 衫裤跑路 2009-01-20 13:04
    关注

    Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class:

    class Base 
    {
        // some virtual methods
    };
    
    class Derived : public Base
    {
        ~Derived()
        {
            // Do some important cleanup
        }
    };
    

    Here, you'll notice that I didn't declare Base's destructor to be virtual. Now, let's have a look at the following snippet:

    Base *b = new Derived();
    // use b
    delete b; // Here's the problem!
    

    Since Base's destructor is not virtual and b is a Base* pointing to a Derived object, delete b has undefined behaviour:

    [In delete b], if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

    In most implementations, the call to the destructor will be resolved like any non-virtual code, meaning that the destructor of the base class will be called but not the one of the derived class, resulting in a resources leak.

    To sum up, always make base classes' destructors virtual when they're meant to be manipulated polymorphically.

    If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and nonvirtual; by doing so, the compiler won't let you call delete on a base class pointer.

    You can learn more about virtuality and virtual base class destructor in this article from Herb Sutter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真