This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

operator delete [] and virtual destructors


G++ version ....... 2.95.2 19991024 (release)
Machine ........... FreeBSD 3.4
Compile options ... none

This concerns overloading operator delete [] in combination with
virtual destructors. The code below defines two classes, A and B
where B inherits A. Both overloads operator delete [] and prints
a message so I can see which one is called. main() allocates a
single B object and a B vector. Then these are deleted when referring
only to their baseclass A.

Since A has a virtual destructor, both the B- and A-destructor is
called correctly for the single B object and for all elements of
the B vector. For the single B object, the compiler apparently
calls the B::operator delete, which should be correct behavior.

But, for the B *vector*, the compiler calls A::operator delete [].
Shouldn't it call B::operator delete [], just like it calls
B::operator delete for single B-objects?

Code and output below.

Regards,
          Mattias Backén

----------------------------

#include <iostream.h>

class A
{
public:
   virtual ~A()
   {
   }
   static void operator delete (void *a)
   {
      cerr << "A::operator delete (void *)" << endl;
      ::operator delete (a);
   }
   static void operator delete [] (void *a)
   {
      cerr << "A::operator delete [] (void *)" << endl;
      ::operator delete (a);
   }
};

class B : public A
{
public:
   static void operator delete (void *a)
   {
      cerr << "B::operator delete (void *)" << endl;
      ::operator delete (a);
   }
   static void operator delete [] (void *a)
   {
      cerr << "B::operator delete [] (void *)" << endl;
      ::operator delete (a);
   }
};

void del(A *o)
{
   delete o;
}

void vdel(A *o)
{
   delete[] o;
}

main()
{
   B *o1 = new B;
   B *o2 = new B[2];

   del(o1);
   vdel(o2);
}

------------------------------

B::operator delete (void *)
A::operator delete [] (void *)

------------------------------

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]