Program crash: GC destroys an object unexpectedly
jfondren
julian.fondren at gmail.com
Tue Sep 21 20:28:33 UTC 2021
On Tuesday, 21 September 2021 at 20:17:15 UTC, eugene wrote:
> Now, change operation order in the main like this:
>
> ```d
> void main(string[] args) {
>
> auto Main = new Main();
> auto stopper = new Stopper();
>
> Main.run();
> stopper.run();
> ```
>
> ```
> d-lang/edsm-in-d-simple-example-2 $ ./test | grep STOPPER
> 'STOPPER' registered 5 (esrc.Signal)
> 'STOPPER' registered 6 (esrc.Signal)
> 'STOPPER @ INIT' got 'M0' from 'SELF'
> 'STOPPER' enabled 5 (esrc.Signal)
> 'STOPPER' enabled 6 (esrc.Signal)
> ```
>
> Everything is Ok now,
I don't think this is reliably OK. If you're not using Stopper
later in the function, and if there are no other references to
it, then the GC can collect it. It just has no obligation to
collect it, so minor differences like this might prevent that
from happening for particular compilers/options/versions.
C# and Go have 'keepalive' functions to avoid similar behavior,
and Java's just as aggressive about potential collection. It's
just something that mostly doesn't matter until it becomes an
incredibly weird bug with code like yours.
More information about the Digitalmars-d-learn
mailing list