Virtual destructor: is it required when not dynamically allocated memory?

后端 未结 6 758
情书的邮戳
情书的邮戳 2020-12-05 07:53

Do we need a virtual destructor if my classes do not allocate any memory dynamically ?

e.g.

class A
{
      private: 
      int a;
      int b;

             


        
6条回答
  •  遥遥无期
    2020-12-05 08:34

    Freeing memory is not the only critical function a destructor can perform. It can also be used to reset global state for instance. Not doing this won't leak memory but could potentially cause other issues in your program.

    Additionally, even if your destructor doesn't do anything useful today, it may at some point in the future. There's no real reason to avoid a virtual destructor if you have inheritance so why not just add it and sleep better at night?

提交回复
热议问题