What should happen here?

Paul Backus snarwin at gmail.com
Mon Sep 20 18:55:25 UTC 2021


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.

IMO all of the options are valid.

The GC gives no guarantees about when or if it will finalize 
GC-allocated objects, so both option 1 and 3 are valid.

Option 2 at first seems like it should be invalid, but since `c` 
is never accessed after initialization, the compiler is free to 
remove the initialization as a dead store, which would allow the 
GC to collect the `new C` object prior to the end of `c`'s 
lifetime.

I would expect to see either 1 or 3 with optimizations disabled, 
and possibly 2 with optimizations enabled. I would be surprised 
to see 4, since dead-store elimination shouldn't depend on 
entropy at runtime.


More information about the Digitalmars-d mailing list