Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing virtual destructor in base interface class?

I have a class deriving (public) from IUnknown, whose definition (from file include/unknwnbase.h in MinGW 4.9.2) I paste below:

extern "C++" {
  MIDL_INTERFACE("00000000-0000-0000-C000-000000000046")
  IUnknown {
  public:
    BEGIN_INTERFACE
    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) = 0;
    virtual ULONG STDMETHODCALLTYPE AddRef(void) = 0;
    virtual ULONG STDMETHODCALLTYPE Release(void) = 0;

    template<class Q>
    HRESULT STDMETHODCALLTYPE QueryInterface(Q **pp) {
      return QueryInterface(__uuidof(Q), (void **)pp);
    }
    END_INTERFACE
  };
}

When I compile the derived class, I get the following warning (which in the OpenCV project are treated as error):

base class 'struct IUnknown' has accessible non-virtual destructor [-Werror=non-virtual-dtor]

I struggle to understand if this is a bug of MinGW (missing virtual destructor) or something else that could be circumvented in the way IUnknown was derived. The OpenCV project is built in several other environments where this warning does not pop up...

like image 896
Antonio Avatar asked Aug 23 '26 12:08

Antonio


1 Answers

In the context of COM, lifetime management of objects (and associated cleanup) happens using the AddRef() and Release() methods of IUnknown, via reference counting.

Each COM object has a reference count associated with it. When an object's reference count reaches 0 (after e.g. several clients of the object have properly called Release() on some COM interface pointer), the object is destroyed. In other words, COM objects are not destroyed in the usual C++ way of calling e.g. delete on a base class pointer (and thus requiring proper virtual destructors in base classes).
(And, in fact, you can't just call new for allocating a COM object. There's more COM machinery that is required.)

In other words, when you're done with a COM interface pointer, you just call Release() on it. So there's no need of virtual destructors to be defined in "base classes", like the IUknown interface, or other COM interfaces.

So, I suspect that warning is a bug somewhere in your MinGW toolchain.

You're not supposed to modify the definition of IUnknown in the Windows SDK header file you cited, neither should you add a virtual destructor in custom COM interfaces you may define for your purposes.

like image 126
Mr.C64 Avatar answered Aug 26 '26 07:08

Mr.C64



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!