In Classes and objects§
See primary documentation in context for Destruction.
Raku is a garbage collecting language. This means that one usually doesn't need to care about cleaning up objects, because Raku does so automatically. Raku does not give any guarantees as to when it will clean up a given object though. It usually does a cleanup run only if the runtime needs the memory, so we can't rely on when it's going to happen.
To run custom code when an object is cleaned up one can use the DESTROY submethod. It can for example be used to close handles or supplies or delete temporary files that are no longer going to be used. As garbage collection can happen at arbitrary points during the runtime of our program, even in the middle of some totally unrelated piece of code in a different thread, we must make sure to not assume any context in our DESTROY submethod.
my $in_destructor = 0; class Foo { submethod DESTROY { $in_destructor++ } } my $foo; for 1 .. 6000 { $foo = Foo.new(); } say "DESTROY called $in_destructor times";
This might print something like DESTROY called 5701 times and possibly only kicks in after we have stomped over former instances of Foo a few thousand times. We also can't rely, on the order of destruction.
Same as TWEAK: Make sure to always declare DESTROY as a submethod.