Destructors for C++ Interface-like classes

前端 未结 6 960
甜味超标
甜味超标 2020-12-30 23:20

Starting to use PC-Lint on an existing code base (fear and trepidation).

One thing that it complains about is the following:

 class IBatch
 {
 public         


        
相关标签:
6条回答
  • 2020-12-30 23:59

    A base class destructor should be either public and virtual, or protected and nonvirtual.

    (Herb Sutter, Guru of the Week #18: "Virtuality")

    0 讨论(0)
  • 2020-12-31 00:07

    So, the question: when you create Interface classes like the above, do you always include a virtual destructor? Why? (is it a style or a coding error?)

    Well it depends really. If you ever call delete on an IBatch pointer it probably won't do what you are expecting. Of course if you have something like virtual Init/Shutdowns or AddRef/Releases then its not really a problem.

    0 讨论(0)
  • 2020-12-31 00:10

    Coding error - The destructor for your derived class will never get called if called via pointer to base class.

    When you implement IBatch and you refer to your derived class by a pointer to a base class (pointer to IBatch) and you call delete on that pointer to base class you might end up with memory leak because the destructor for your derived class will never get called.

    The basic rule is when a class has at least one virtual method it needs to have virtual destructor.

    class IBatch
    {
        public:
           virtual void f() = 0;
    };
    
    class A : public IBatch
    {
        public:
           void f() {}
           ~A() {}
    };
    
    IBatch * a = new A();
    a->f();    // calls A::f()
    delete a;  // calls IBatch::~IBatch() not A::~A()
    
    0 讨论(0)
  • 2020-12-31 00:14

    If there are virtual functions, there needs to be a virtual destructor. Always. It does not matter that it's only an interface class -- it still needs the virtual destructor.

    Either that, or it needs a protected nonvirtual destructor. But then you cannot delete the object using the interface pointer.

    0 讨论(0)
  • 2020-12-31 00:21

    Compiler puts default destructor that is not virtual, which implies that a 'delete' on a pointer to the virtual base class will succeed with a resulting memory leak. Therefore, it is an implementation flaw, neither style or coding error.

    0 讨论(0)
  • 2020-12-31 00:24

    A class with virtual functions but no virtual destructor is suspect, and most likely wrong: see a good and more precise explanation here.

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