Suppress delete-non-virtual-dtor warning when using a protected non-virtual destructor

后端 未结 2 1789
面向向阳花
面向向阳花 2021-01-18 01:17

I have a pure abstract interface class, and a derived class which implements the interface.

struct Foo
{
    virtual void doStuff() = 0;
};

struct Bar : Foo         


        
相关标签:
2条回答
  • 2021-01-18 01:31

    The compiler is telling you that the problem is in Bar not in Foo. If you were to have another class that inherits from Bar say Baz:

    struct Baz : public Bar
    {
      void doStuff() override { }
    };
    

    This could lead to undefined behavior such as the case

    int main()
    {
        Bar* bar_ptr = new Baz();
        bar_ptr->do_stuff();
        delete bar_ptr; // uh-oh! this is bad!
    }
    

    because the destructor in Bar is not virtual. So the solution is to mark Bar as final as has been suggested, or make the destructor in Bar virtual (since it's public) or make it protected in accordance with Herb's suggestions.

    0 讨论(0)
  • 2021-01-18 01:45

    Marking the class final remove the warning.

    struct Bar final : Foo
    {
        void doStuff() override { }
    };
    
    int main()
    {
        Bar* f = new Bar;
        f->doStuff();
        delete f;
    }
    

    Demo

    0 讨论(0)
提交回复
热议问题