package My::Inner; # Usage: use My::Inner qw< _wrap _unwrap _incRefs _decRefs >; # Defines the using class as an inner class wrapped by some other class # (the wrapping class must use My::Outer). # The using class must define the following methods: # _new: the constructor # _free: breaks ref cycles if all related inner objects are unref'd #+ _incRefs: increments inner object's ref count #+ _decRefs: decrements inner object's ref count, returning result #+ If using class creates blessed hashes and wants $obj->{refs} to be the ref #+ count, then it can just import the _incRefs and _decRefs methods. ## (Not: "Using class must create blessed hashes so $obj->{ref}, ## $obj->{wrapper} work.") use Exporter 'import'; BEGIN { our @EXPORT_OK= qw< _wrap _unwrap _incRefs _decRefs >; } sub _wrap { my( $in, $class )= @_; my $out= bless \$in, $class; $in->_incRefs(); ## if( $class ) { ## $in->{wrapper}= $class ## } else { ## $class= $in->{wrapper}; ## } return $out; } sub _unwrap { my( $in )= @_; if( ! $in->_decRefs() ) { $in->_free(); } } #+ (Added below code) sub _incRefs { my( $in )= @_; $in->{refs}++; } sub _decRefs { my( $in )= @_; return --$in->{refs}; }