Garbage Collection with destroy Methods
As described in the section Garbage Collection, Circular References, and Weak
References in Chapter 8, a variable that refers to itself (or multiple
variables that refer to one another indirectly) will not be freed until
the program (or embedded interpreter) is about to exit. If you want to
reclaim the memory any earlier, you usually have to explicitly break the
reference or weaken it using the Scalar::Util module.
With objects, an alternative solution is to create a container
class that holds a pointer to the self-referential data structure.
Define a DESTROY method for the
containing object’s class that manually breaks the circularities in the
self-referential structure. You can find an example of this in Recipe
13.13, “Coping
with Circular Data Structures Using Weak References” of
Perl
Cookbook.
When an interpreter shuts down, all its objects are destroyed,
which is important for multithreaded or embedded Perl applications.
Objects are always destroyed in a separate pass before ordinary
references. This is to prevent DESTROY methods from using references that
have themselves been destroyed. (And also because plain references are
only garbage collected in embedded interpreters, since exiting a process
is a very fast way of reclaiming references. But
exiting won’t run the object destructors, so Perl does that first.)
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access