[cfe-dev] Dynamic memory allocation and deleted definitions

David Blaikie dblaikie at gmail.com
Wed Nov 13 13:15:44 PST 2013


On Wed, Nov 13, 2013 at 12:22 PM, Rahul Jain <1989.rahuljain at gmail.com>wrote:

> 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?
>

Precisely - whether or not an exception occurs is a runtime property, so
the compiler can't know whether it will happen and needs to emit the code
to handle it regardless.


>
> 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?
>

It's possible that GCC is just being lazy, or that there's a requirement
that the default ctor is 'nothrow' then no dtors need be called.


> 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?
>

I'd have to go track down the wording. I don't know off hand.


>
> 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/20131113/d66e239f/attachment.html>


More information about the cfe-dev mailing list