scope(exit) and destructor prioity

Eugene Wissner belka at caraus.de
Mon Sep 18 21:18:30 UTC 2017


On Monday, 18 September 2017 at 20:55:21 UTC, Sasszem wrote:
> On Monday, 18 September 2017 at 20:30:20 UTC, Jerry wrote:
>> On Monday, 18 September 2017 at 20:26:05 UTC, Sasszem wrote:
>>>  [...]
>>
>> It's called inbetween the destructors of wherever you put the 
>> scope(exit).
>>
>> import std.stdio;
>>
>> struct De
>> {
>> 	~this() { writeln("De"); }
>> }
>>
>> void main()
>> {
>> 	De a;
>> 	scope(exit) writeln("scope exit");
>> 	De b;
>> }
>>
>>
>> Output:
>> De
>> scope exit
>> De
>
> If I write "auto a = new De()", then it calls the scope first, 
> no matter where I place it.

If I write "auto a = new De()" I have the same behaviour. If I 
have "auto b = new De()" aswell, then yes, destructors are called 
after scope exit.
Because you allocate on the heap with new, the destructor isn't 
called at the end of the scope at all. It is called later by the 
GC.

Try to put variable declarations with destructor after "scope 
exit" or destroy them manually with "destroy(a)".

See https://dlang.org/spec/statement.html#scope-guard-statement 
for order of calling destructors at the end of scope.


More information about the Digitalmars-d-learn mailing list