[cfe-dev] Dynamic memory allocation and deleted definitions

Halfdan Ingvarsson halfdan at sidefx.com
Wed Nov 13 10:52:50 PST 2013


On 13-11-13 01:39 PM, Rahul Jain wrote:
> But why will the destructor get called if the array is not explicitly 
> deleted?

Because if you new[] an array of objects, and the constructor of one of 
the objects throws an exception, then the already constructed objects 
will get destructed (destroyed?).

Example:
#include <iostream>

int i = 0;
struct A
{
     A() { id = i++; if(id == 5) throw std::exception(); }
     ~A() { std::cout << "Destroying " << id << "\n"; }

     int id;
};

int main()
{
     try
     {
     A *a = new A[10];
     }
     catch(...) {}
     return 0;
}

  - ½




More information about the cfe-dev mailing list