Regarding destruction order during garbage collection:
If an object is destructed by the garbage collector, it's part of
a reference cycle with other things but with no external
references. If there are other objects with destroy
functions in the same cycle, it becomes a problem which to call
first.
E.g. if this object has a variable with another object which
(directly or indirectly) points back to this one, you might find
that the other object already has been destructed and the variable
thus contains zero.
The garbage collector tries to minimize such problems by defining
an order as far as possible:
If an object A contains an lfun::destroy and an object B does
not, then A is destructed before B.
If A references B single way, then A is destructed before B.
If A and B are in a cycle, and there is a reference somewhere
from B to A that is weaker than any reference from A to B, then
A is destructed before B.
Weak references (e.g. set with set_weak_flag() ) are considered
weaker than normal references, and both are considered weaker
than strong references.
Strong references are those from objects to the objects of their
lexically surrounding classes. There can never be a cycle
consisting only of strong references. (This means the gc never
destructs a parent object before all children have been
destructed.)
An example with well defined destruct order due to strong
references:
class Super {
class Sub {
static void destroy() {
if (!Super::this)
error ("My parent has been destructed!\n");
}
}
Sub sub = Sub();
static void destroy() {
if (!sub)
werror ("sub already destructed.\n");
}
}
The garbage collector ensures that these objects are destructed in
an order so that werror
in Super
is called and not
error
in Sub
.