Destructors for C++ Interface-like classes

前端 未结 6 1010
甜味超标
甜味超标 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-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()
    

提交回复
热议问题