[cfe-dev] is delete on abstract with non-virtal ever safe?

Henry Miller hank at millerfarm.com
Mon Jul 23 07:29:31 PDT 2012


I'm trying to settle an argument we are having at work.  Right now our
code doesn't compile with clang because of a code like below.

I understand (and agree with) the warning, however the owner of this
code argues that only the default destructors are used, and they have
procedures in place to ensure that no derived class will ever have
members that need destruction.  So the question is he correct that the
destructor for derived doesn't need to be called?  If so is there a way
to shut clang up without disabling the warning (which has already found
several real problems I've since corrected).  If not can someone point
out why we need a virtual destructor in this case.

    class base
    {
    public:
      virtual void operator() () const = 0;
    };

    template<typename T>
    class derived : public base
    {
    public:
       derived(T& d) : data(d) {}
       void operator() () const {data.DoSomething();}

    private:
       T& data; // note that the only data is a reference!
    };

    class myClass
    {
    public:
       void DoSomething() {}
    };

    int main(int, char **)
    {
        myClass cl;
        base* foo = new derived<myClass>(cl);
        delete foo;
    }

clang++ ex.cpp
ex.cpp:29:5: warning: delete called on 'base' that is abstract but has
      non-virtual destructor [-Wdelete-non-virtual-dtor]
    delete foo;

Note, we are comparing to gcc 4.4.  I'm given to understand that gcc4.7
also has this warning, but we don't have the ability to upgrade right
now.

-- 
  Henry Miller
  hank at millerfarm.com



More information about the cfe-dev mailing list