rsteinke has asked for the wisdom of the Perl Monks concerning the following question:

I'm dealing with a situation where I'm passed a blessed object in a function call. I store a weakened reference to that object, since I don't want to extend its lifespan. Is there some way I can be notified when that object is destroyed? The best I've come up with is restricting the function to only take blessed hashes. I insert a second blessed object into the first object's hash table, then stick the code-to-call-on-destruction into the second object's DESTROY function. Is there anything I could do that would be more general?

Replies are listed 'Best First'.
Re: Object destruction notification
by lachoy (Parson) on Jun 26, 2002 at 09:59 UTC

    If you have control over the first object, you can use Class::Observable:

    package FirstObject; use base qw( Class::Observable ); ... sub DESTROY { my ( $self ) = @_; $self->notify_observers( 'DESTROY' ); } package SecondObject; sub take_first_object { my ( $class, $first_object ) = @_; $first_object->add_observer( $class ); } sub update { my ( $class, $first_object, $type ) = @_; return unless ( $type eq 'DESTROY' ); ... do stuff with $first_object ... }

    If you don't have control over the first object and it's well designed, maybe you could subclass it to add the Observable behavior.

    Chris
    M-x auto-bs-mode

Re: Object destruction notification
by rjray (Chaplain) on Jun 26, 2002 at 06:00 UTC

    If the class can be cleanly sub-classed, then you can write a sub-class that allows you to put in hooks at the DESTROY level, before calling $self->SUPER::DESTROY for the "real" destruction. Given that you are only keeping hold of a weak reference, that may be your best bet.

    Alternately, if you have developmental control over the class in question, you could develop a super-class with the functionality built in to the DESTROY method, and inherit from that in the main class. That requires writing the target class to either have no built-in destructor, or to make sure to call the super-class destructor. But it also means that you can use the interface (to use the Java terminology :-) with other classes, as well.

    --rjray

      I realized upon re-reading this, that you aren't the party responsible for allocating the object (or rather, at this point in the application logic, that knowledge seems to be abstracted away). That makes for a more complex problem, in which case I would probably go the same route you already have. To my knowledge, the only externally-predictable event upon object destruction is the calling of the DESTROY method (if it exists) within that class/package. There isn't (that I know of) a more universal hook point at which you can monitor general object disposal, simply for the sake of catching the few that you care about.

      --rjray