[Bug c++/15214] New: Warning non-virtual-dtor too strict

tmarshall at real dot com gcc-bugzilla@gcc.gnu.org
Fri Apr 30 00:35:00 GMT 2004


It seems to me that it is safe to have virtual functions and a non-virtual dtor
if the dtor can only be invoked by methods within the class.  That is, the dtor
must be private and the class must not declare any friends.

Sample code:

#include <stdio.h>

class A
{
public:
    A() : m_ref(0) { printf("a::ctor\n"); }

    virtual int addref(void);
    virtual int release(void);

private:
    ~A() { printf("a::dtor\n"); }

protected:
    int m_ref;
};

int A::addref(void)
{
    return ++m_ref;
}
int A::release(void)
{
    int ref = --m_ref;
    if (ref == 0) delete this;
    return ref;
}
 
int main(void)
{
    A* a = new A;
    a->addref();
    a->release();
    return 0;
}

Patch:

--- class.c.orig        2004-04-29 16:51:53.000000000 -0700
+++ class.c     2004-04-29 16:51:55.000000000 -0700
@@ -5102,7 +5102,17 @@
 
   if (warn_nonvdtor && TYPE_POLYMORPHIC_P (t) && TYPE_HAS_DESTRUCTOR (t)
       && DECL_VINDEX (TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (t), 1)) == NULL_TREE)
-    warning ("`%#T' has virtual functions but non-virtual destructor", t);
+    {
+      tree dtor = TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (t), 1);
+
+      /* Warn only if the dtor is non-private or the class has friends */
+      if (!TREE_PRIVATE (dtor) ||
+         (CLASSTYPE_FRIEND_CLASSES (t) ||
+          DECL_FRIENDLIST (TYPE_MAIN_DECL (t))))
+       {
+         warning ("%#T' has virtual functions but non-virtual destructor", t);
+       }
+    }
 
   complete_vars (t);

-- 
           Summary: Warning non-virtual-dtor too strict
           Product: gcc
           Version: 3.4.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P2
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: tmarshall at real dot com
                CC: gcc-bugs at gcc dot gnu dot org


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=15214



More information about the Gcc-bugs mailing list