You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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).
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Manual
free()is error-prone. We can use Perl'sDESTROYphase to automate it.The Recipe
How It Works
When the last reference to
$safedisappears, Perl callsDESTROY. 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).All reactions