default override of virtual destructor

前端 未结 7 1031
孤独总比滥情好
孤独总比滥情好 2021-02-01 12:50

Everyone knows that the desructor of base class usually has to be virtual. But what is about the destructor of derived class? In C++11 we have keyword \"override\" and ability t

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 13:11

    There is (at least) one reason for using override here -- you ensure that the base class's destructor is always virtual. It will be a compilation error if the derived class's destructor believes it is overriding something, but there is nothing to override. It also gives you a convenient place to leave generated documentation, if you're doing that.

    On the other hand, I can think of two reasons not to do this:

    • It's a little weird and backwards for the derived class to enforce behavior from the base class.
    • If you define a destuctor in the header (or if you make it inline), you do introduce the possibility for odd compilation errors. Let's say your class looks like this:

      struct derived {
          struct impl;
          std::unique_ptr m_impl;
          ~derived() override = default;
      };
      

      You will likely get a compiler error because the destructor (which is inline with the class here) will be looking for the destructor for the incomplete class, derived::impl.

      This is my round-about way of saying that every line of code can become a liability, and perhaps it's best to just skip something if it functionally does nothing. If you really really need to enforce a virtual destructor in the base class from the parent class, someone suggested using static_assert in concert with std::has_virtual_destructor, which will produce more consistent results, IMHO.

提交回复
热议问题