Can the default destructor be generated as a virtual destructor automatically?

前端 未结 7 1543
轮回少年
轮回少年 2021-01-31 07:30

Can the default destructor be generated as a virtual destructor automatically?

If I define a base class but no default destructor, is there a default virtual destructor

7条回答
  •  梦谈多话
    2021-01-31 07:39

    No, all destructor's are by default NOT virtual.

    You will need to define a virtual destructor on all the base classes

    In addition to that.

    To quote Scott Meyers in his book "Effective C++":

    The C++ language standard is unusually clear on this topic. When you try to delete a derived class object through a base class pointer and the base class has a non-virtual destructor (as EnemyTarget does), the results are undefined

    In practice, it's usually a good idea to define a class with a virtual destructor if you think that someone might eventually create a derived class from it. I tend to just make all classes have virtual destructor's anyway. Yes, there is a cost associated with that, but the cost of not making it virtual more often that not out weighs a measly bit of run-time overhead.

    I suggest, only make it non-virtual when you're absolutely certain that you want it that way rather than the rely on the default non-virtual that the compilers enforce. You may disagree, however (in summary) I recently had a horrid memory leak on some legacy code where all I did was add a std::vector into one of the classes that had existed for several years. It turns out that one of it's base classes didn't have a destructor defined (default destructor is empty, non-virtual!) and as no memory was being allocated like this before no memory leaked until that point. Many days of investigation and time wasted later...

提交回复
热议问题