What is going on here?

via Digitalmars-d digitalmars-d at puremagic.com
Wed Mar 4 11:16:37 PST 2015

On Wednesday, 4 March 2015 at 17:19:31 UTC, Steven Schveighoffer 
> On 3/4/15 11:32 AM, "Marc =?UTF-8?B?U2Now7x0eiI=?= 
> <schuetzm at gmx.net>" wrote:
>> On Wednesday, 4 March 2015 at 15:43:15 UTC, Steven 
>> Schveighoffer wrote:
>>> On 3/4/15 8:43 AM, Shachar Shemesh wrote:
>>>> I'd expect A's destructor to run, which does not seem to be 
>>>> the case.
>>> I believe destructors are not run when you throw inside a 
>>> constructor.
>>> So plan to deallocate if the ctor throws:
>>> a = A(var + 1);
>>> scope(failure) destroy(a);
>> The spec says [1], that the first write to a field in a class's
>> constructor is a construction, not an assignment. I assume 
>> this applies
>> to structs as well. If so, this implies that the compiler 
>> already knows
>> at each point which fields are already constructed. Why 
>> doesn't it
>> automatically insert appropriate destructor calls then?
>> [1] http://dlang.org/class.html#field-init
> That is talking about initializing immutable fields.

That's true, but I was going to argue that if the compiler is 
able to check this for immutable fields, there is no reason why 
it couldn't also do it for mutable ones. But now I see that it 
only uses an imprecise heuristic that is probably too coarse to 
extend it to mutable fields. In fact, I even found a loop-hole, 
which I've filed here:


> The dtor is not called when the exception is thrown, but this 
> doesn't seem to be in the spec (I don't remember where I read 
> it, but I'm sure it's an intentional decision). D provides a 
> mechanism to destroy partially constructed objects, use 
> scope(failure).

Oh no, another hidden trap :-( `scope(failure)` is only a 
workaround if you're aware of it. I think the heuristic for 
immutable fields could be adapted to be applicable to mutable 
fields: the first assignment to a field must not be inside a loop 
or behind a label.

More information about the Digitalmars-d mailing list