I read the “Programming Perl” book which is rather complicated in some places. And one of those places is the section “Instance Destructors” in the 12th chapter “Objects”. This section says:
- Objects in Perl are destroyed when there is no more references to them.
- There is an opportunity to capture control just before object is going to be recycled by defining
DESTROYmethod in its class. - Although destructors are rarely needed in Perl, some objects may have, for instance, filehandles or database connections, which are outside of the memory system. So it is necessary to attend them specially.
- Perl does not do hierarchical destruction.
Then there is a paragraph which I failed to understand:
This only applies to inherited classes; an object that is simply contained within
the current object—as, for example, one value in a larger hash—will be freed
and destroyed automatically. This is one reason why containership via mere ag-
gregation (sometimes called a “has-a” relationship) is often cleaner and clearer
than inheritance (an “is-a” relationship).
I can’t understand what it means. Does it mean that an object that IS NOT simply contained within the current object, WILL NOT be freed and destroyed automatically?
I do know that a DESTROY that is called on the garbage collection is the nearest one and only one. No other overridden DESTROY methods are called when there is no refs to an instance. But, as I understand, the same behavior is expected when a ref to an instance is placed inside another object.
Would someone be so pleasant to construe and to provide a code-example ?
UPDATE:
Actually what I was looking for, was the explanation of the This only applies to inherited classes; words which turned out to be that:
If you have an instance of a class and it has a DESTROY method than that method will override DESTROY methods of a parent class(es), but that does not apply to an object, that is in a has-a relationship with the object in question. Its DESTROY won’t be overridden
Sorry for not clear question, it would better fit to the English Language and Usage. Thanks to everyone.
Rule 1: Objects in Perl are destroyed when there is no more references to them.
Rule 2: There is an opportunity to capture control just before object is going to be recycled by defining DESTROY method in its class.
Rule 4: Perl does not do hierarchical destruction.
Now if
AnotherClasswill be instantiated, only theDESTROYmethod ofAnotherClasswill be called, not theDESTROYmethod ofClass. This is meant with the absence of a hierarchical destruction. This is obvious, as theDESTROYmethod overwrites the previous entry. The originalDESTROYcan be called manuallyUsing a parent class and a child class is a IS-A relationship:
AnotherClassis aClass.If we have YetAnotherClass:
This is a case of aggregation (
Classis a data member ofYetAnotherClass), and a HAS-A relationship.