[cfe-dev] Dynamic memory allocation and deleted definitions

David Blaikie dblaikie at gmail.com
Wed Nov 13 10:46:02 PST 2013


On Wed, Nov 13, 2013 at 10:39 AM, Rahul Jain <1989.rahuljain at gmail.com>wrote:

> But why will the destructor get called if the array is not explicitly
> deleted?
>
> Consider the following piece of code without the deleted definition.
>
> #include<stdio.h>
>
> struct A
> {
>   ~A() {
>   printf ("Inside destructor\n");
>   }
> };
>
>
> int main()
> {
>   A* ap = new A[5];
>   delete []ap;
> }
>
> On executing this "Inside destructor" gets printed 5 times.
>
> But if we remove the delete statement, nothing gets printed i.e the
> destructor is never run.
>
> I did not get what you meant by saying "if A's ctor throws on one of the
> constructed objects in the array, the dtor for the previous array elements
> needs to be run"?
>

Are you familiar with C++ exceptions?

Try something like this:

int i = 0;

struct A {
  A() { if (++i == 2) { throw 0; } }
  ~A() { printf("Inside destructor\n"); }
};

int main() {
  A *ap = new A[2];
}

Even without the delete statement, you should see "Inside destructor" print
once.

As I said, it's possible that if the constructor is 'nothrow' then Clang is
meant to not need the dtor here, I haven't checked the exact wording of the
standard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20131113/bd7e0e68/attachment.html>


More information about the cfe-dev mailing list