[cfe-dev] Dynamic memory allocation and deleted definitions

Rahul Jain 1989.rahuljain at gmail.com
Wed Nov 13 12:22:57 PST 2013


Thanks David, Halfdan for your valuable inputs.
Just need some more clarification so that I get the complete thing.


Yes I understood that when we new[] an array of objects and the constructor
of one of the objects throws, the already constructed objects should be
destructed as the complete array construction could not get through
successfully.

But assume if the constructor is not throwing, and all the objects of the
array get constructed completely, than where does the need of the
destructor call arise from?

Is it the possibility of a runtime throw which prevents the compiler from
compiling a deleted destructor definition in case of an array allocation?

Also what exactly is the difference in this context when we define a
default constructor in our class vs a synthesized default constructor in
our class?

g++ seems to accept the synthesized version whereas errors when one defines
a default constructor(as Halfsan mentioned above), whereas clang rejects
both the versions. Who is at fault here?

Thanks,
Rahul



On Thu, Nov 14, 2013 at 12:22 AM, Halfdan Ingvarsson <halfdan at sidefx.com>wrote:

> 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;
> }
>
>  - ½
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20131114/37ab4772/attachment.html>


More information about the cfe-dev mailing list