What should happen here?
Walter Bright
newshound2 at digitalmars.com
Sat Sep 25 00:12:28 UTC 2021
On 9/20/2021 11:26 AM, Steven Schveighoffer wrote:
> [...]
1, 2, or 3 are all valid outcomes.
The lifetime of a GC allocated object ends when there are no longer live
references to it. Live references can end before the scope ends, this is called
"non-lexical scoping". That does not imply that that is when the class
destructor is run. The class destructor runs at some arbitrary time *after*
there are no longer references to it.
The GC is not obligated to run a collection cycle upon program termination (a
laxity intended to improve shutdown performance), and hence it is not obliged to
run the class destructors.
The inevitable consequence of this is:
Do *not* use the GC to manage non-memory resources.
But if you must do it anyway, use the "destroy" and "free" GC special functions.
Of course, if you decide to use these functions, it's up to you to ensure
resources are free'd exactly once.
https://dlang.org/phobos/object.html#.destroy
https://dlang.org/phobos/core_memory.html#.GC.free
P.S. A live reference is one where there is a future use of it. A dead reference
is one where there isn't a future use. The `c` variable is a dead reference
immediately after it is initialized, which is why optimizers delete the
assignment. The `new C` return value is dead as soon as it is created.
P.P.S. Attempting to deduce the GC's rules from observing its behavior is very
likely a path to frustration and errors, because its observed behavior will not
make sense (and will appear random) unless one understands the above explanation.
P.P.S. Do not conflate class destructors with struct destructors. The latter
follow RAII rules, the former does not.
More information about the Digitalmars-d
mailing list