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

后端 未结 2 1792
面向向阳花
面向向阳花 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.

提交回复
热议问题