What should happen here?
Johan
j at j.nl
Mon Sep 20 18:46:50 UTC 2021
On Monday, 20 September 2021 at 18:38:03 UTC, Johan wrote:
> On Monday, 20 September 2021 at 18:26:59 UTC, Steven
> Schveighoffer wrote:
>> Without any context, what do you think should happen here?
>>
>> ```d
>> import std.stdio;
>> import core.memory;
>> class C
>> {
>> ~this() { writeln("dtor"); }
>> }
>>
>> void main()
>> {
>> auto c = new C;
>> foreach(i; 0 .. 10000) GC.collect;
>> writeln("end of main");
>> }
>> ```
>>
>> Option 1:
>> ```
>> end of main
>> dtor
>> ```
>>
>> Option 2:
>> ```
>> dtor
>> end of main
>> ```
>>
>> Option 3:
>> ```
>> end of main
>> ```
>>
>> Option 4:
>> Option 1 or 2, depending on entropy.
>>
>
> I believe all options are valid, because there is no guarantee
> if and when class destructors are called.
> I'm guessing without optimization, option 3 will happen most.
> With optimization turned on, option 2. Or maybe the object is
> put on the stack (`scope` or LDC's heap->stack optimization)
> and so option 1 happens?
FWIW I believe option 1 should only happen with this "to stack"
optimization (object lifetime provably confined to the function),
because we are not obliged by the language spec to collect
garbage after `main` ends (so it's best for performance to not
collect).
-Johan
More information about the Digitalmars-d
mailing list