C++ dll interface class with non virtual destructor

815 views Asked by At

I develop a windows app which loads dll plugins, I would like these plugins to be compilable with other compilers than mine (MinGW)

So I have implemented a plugin interface class PluginInterface, which has only pure virtual functions. The plugin exports two C functions, one for creating an object which derives from PluginInterface and return a pointer on it, and another function for deleting the object.

The problem is if I have a virtual destructor to PluginInterface, the interface becomes non-binary compatible between compilers (for instance MinGW/MSVC). If I have no destructor defined (or a default destructor), gcc warns about deleting a polymorphic object which has non-virtual destructor, and that it may cause undefined behavior.

How can I cleanly remove that warning and be sure that no undefined behavior will occur?

Thanks

2

There are 2 answers

1
NathanOliver On

If you are going to inherit from PluginInterface you need to have a virtual destructor if you are using virtual functions. Marking the destructor virtual is the only way to destroy a derived object that is cast as a base object. If the destructor is not virtual then only the base part of the derived object would be destroyed and the rest would be in an indeterminate state which is undefined behavior.

4
Patryk Lipski On

But why you need destructor in class that is actually an interface? I think you should only export two functions from dll (Query and Release). Query could instantiate object on DLL side and return PluginInterface pointer to that newly created object. Release could call destructor also on DLL side, directly on object. You can also implement DLL as singleton to make sure that your plugin provides only one instance of given object and you don't have to worry about counting them.