[cfe-dev] operator delete[] does not call derived class destructor

Howard Hinnant hhinnant at apple.com
Sun May 20 11:11:39 PDT 2012


On May 20, 2012, at 2:01 PM, Dmitri Gribenko wrote:

> On Sun, May 20, 2012 at 11:20 AM, bd satish <bdsatish at gmail.com> wrote:
>> Base* ptr = new Derived[3];
>> delete [] ptr;
> 
> Hello,
> 
> It seems to me that this is undefined behavior:
> 
> [expr.delete]/3: In the second alternative (delete array) if the
> dynamic type of the object to be deleted differs from its static type,
> the behavior is undefined.

That's correct.  I just wanted to add that if you use std::unique_ptr (available in libc++ / -stdlib=libc++), then this run time error will be converted into a compile-time error:

#include <iostream>
#include <memory>

class Base
{
public:
 Base()    {    }

 virtual ~Base() {
   std::cout << "In destructor " <<  __func__  << std::endl;
 }
};

class Derived: public Base
{
public:
 Derived() {}

 ~Derived()  {
   std::cout << "In destructor for " <<  __func__ << std::endl;
 }
};

int main()
{
  std::unique_ptr<Base[]> ptr(new Derived[3]);
}

test.cpp:26:27: error: no matching constructor for initialization of 'std::unique_ptr<Base []>'
  std::unique_ptr<Base[]> ptr(new Derived[3]);
                          ^   ~~~~~~~~~~~

Howard




More information about the cfe-dev mailing list