|more useful options|
Garbage collected class attributes with inside out classes.by kyle (Abbot)
|on Mar 01, 2007 at 16:04 UTC||Need Help??|
Having class attributes with an inside out class is pretty straight forward. Just use a regular lexical variable next to the hashes you use to hold your instance attributes. Without some extra logic, however, those variables will hold their values even after the last instance of your class has disappeared.
Say one of those class variables holds a large data structure that you don't want hanging around in memory when it's not needed. You want to have a class attribute that gets garbage collected when the last instance is destroyed.
In my first implementation, each class attribute is held as a reference, and each instance has a copy of that one reference. When the last instance is destroyed, the last reference disappears, and that mammoth data structure gets destroyed too.
What's good: All the work is done at construction, when you are probably doing some initialization work anyway.
What's bad: The initialization is a clutter. The accessors are expensive because of the dereferencing.
An alternate method is to count references in a separate class attribute—a method that is not really specific to inside out objects at all. When the destructor detects that it is destroying the last instance, it undefs each of the class attributes.
What's good: It's fast, clean, and simple to understand.
What's bad: There's an extra variable that you can't get rid of but also isn't part of the core functionality.
I've offered two possibilities here. What do the other monks do in this situation?