Shopping for template languages
An Pham
home at home.com
Wed Aug 7 21:39:06 UTC 2024
On Wednesday, 7 August 2024 at 20:26:07 UTC, matheus wrote:
>
> Anyway, I wish there was a C version or a D option for auto
> free after end of scope for memory manually allocated for
> example.
>
> Matheus.
No need language feature - here is auto free after scope
compile with -debug option
import core.stdc.stdlib : malloc;
import std.stdio : writeln;
struct Foo
{
int x;
}
struct Owned(T)
{
this(void* v) nothrow @nogc
{
debug writeln("constructor");
this.v = cast(T*)v;
}
~this() nothrow @nogc
{
debug writeln("destructor");
import core.stdc.stdlib : free;
if (v)
{
free(v);
debug writeln("free");
}
}
static typeof(this) malloc() nothrow @nogc // same attribute
as stdlib.malloc
{
return typeof(this)(.malloc(T.sizeof));
}
T* v;
alias this=v;
}
void main()
{
{ // Simulate scope
auto foo = Owned!Foo(malloc(Foo.sizeof));
foo.x = 10;
assert(foo.x == 10);
writeln(foo.x);
}
{ // Simulate scope
auto foo = Owned!Foo.malloc;
foo.x = 100;
assert(foo.x == 100);
writeln(foo.x);
}
}
More information about the Digitalmars-d
mailing list