Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an object of a polymorphic class type that has no virtual destructor

I am getting the following error when I try to compile some code from a Third-party SDK.

*Description    Resource    Path    Location    Type
deleting object of polymorphic class type ‘Vendor_sys::VendorCode’ which has non-virtual destructor might cause undefined behaviour [-Werror=delete-non-virtual-dtor]   PnServer.cpp    /PCounter   line 467    C/C++ Problem*

I do not know if its possible to satisfy this condition with only partial knowledge of the Vendor's SDK, where most of the heavy lifting is done in a dll or library object.

My build environment is Eclipse Juno with gpp.

I searched in Google for the error message and did not find any instances of this error.

So, if I cannot modify the black box part of the vendor code, what are my options?

Here is the code that is failing during the make process:

delete pData->unit;
like image 260
bentaisan Avatar asked Oct 21 '12 04:10

bentaisan


People also ask

What happens if destructor is not virtual?

Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior.

Is there a non-virtual destructor?

A C++ class containing virtual member functions has a non-virtual destructor. Since this class has virtual member functions, it will be used as a base class. The use of non-virtual destructors in base classes is dangerous because it can cause objects to be torn down incorrectly.

Does deleting a pointer call the destructor?

Delete invokes the destructor Default destructors call destructors of member objects, but do NOT delete pointers to objects.

Can a class have virtual destructor A Yes No?

Yes, it is possible to have a pure virtual destructor. Pure virtual destructors are legal in standard C++ and one of the most important things to remember is that if a class contains a pure virtual destructor, it must provide a function body for the pure virtual destructor.


1 Answers

Bad news, I am afraid. You should not use that class as a base class. Too many constraints and pitfalls. You might get away with it, but why risk it? File a bug report with the library vendor.

If you do not need polymorphic pointers, include an object of that type in your class, and delegate the member functions you wanted to inherit.

class my_class {
private:
    evil_class evil;
public:
    virtual ~my_class() {/* stuff */}
    virtual int member() { return evil.member(); }
};
like image 118
Jive Dadson Avatar answered Sep 25 '22 19:09

Jive Dadson