Manual free() is error-prone. We can use Perl's DESTROY phase to automate it.

The Recipe

use v5.40;
no warnings 'experimental';
use feature 'class';
use Affix qw[:all];

class AutoPointer {
    field $ptr : reader : param;

    method DESTROY {
        Affix::free($ptr);    # Call C/malloc free()
    }
}

# Usage
{
    my $safe = AutoPointer->new( ptr => malloc(1024) );

    # ... use $safe->ptr ...
    Affix::dump( $safe->ptr, 1024 );
}    # $safe goes out of scope -> DESTROY called -> free() called.

How It Works

When the last reference to $safe disappears, Perl calls DESTROY. By wrapping our raw C pointer in a blessed object, we tie the C memory lifecycle to the Perl variable's scope. This is known as RAII (Resource Acquisition Is Initialization).