Search code examples
c++gccdestructorgcc-warning

How to delete pointer to a class without virtual functions and no inheritance


When a class has virtual method, you need to write a virtual destructor to properly free the memory in the destructor.

In my case, I don't have a virtual method in the class and neither any sub-classes.

When I compile the program using gcc with "-Wdelete-non-virtual-dtor" flag I get a warning. Rewriting the destructor as virtual indeed removes the warning, but I don't want to rewrite the destructor of the class as virtual since it doesn't have any sub-classes. Is there any way to suppress the warning "-Wdelete-non-virtual-dtor" and tell the compiler there is no inheritance - sub-classes for this class? It's not a specific gcc version or gcc question.

UPDATE: Discovered that my class has inheritance of other class that has virtual functions and thus itself has virtual functions.

The accept answer was that I missed that the class is indeed virtual (since it inherits another class with virtual functions). Since it doesn't have sub-classes and should have ones, I can add "final" keyword to the class to solved the issue.

Simple code example:

#include <iostream>

class A {
    public:
    int a;
    virtual void f() {};
};

template<class T> void foo() {
    T *obj = new T;

    delete obj;
}

int main()
{
    foo<A>();
    std::cout << "Done" << std::endl;
}

Adding final to class A - also removed the warning.


Solution

  • Mark the class as final (from C++11).

    Then it can't have a child class, so you don't need to worry about the implications of having a non-virtual destructor. A compiler should be aware of that and suppress the warning.

    Reference: https://en.cppreference.com/w/cpp/language/final