Skip to content

Instantly share code, notes, and snippets.

@rigibun
Created April 7, 2014 14:22
Show Gist options
  • Save rigibun/df2f1fbc15be567df056 to your computer and use it in GitHub Desktop.
Save rigibun/df2f1fbc15be567df056 to your computer and use it in GitHub Desktop.
import std.stdio;
class C
{
this(string arg = "")
{
writeln("constructor is called." ~ arg);
}
~this()
{
writeln("destructor is called.");
}
}
T allocate(T, Args...)(Args args)
{
import std.conv : emplace;
import core.stdc.stdlib : malloc;
auto size = __traits(classInstanceSize, T);
auto memory = malloc(size)[0..size];
if(!memory)
{
import core.exception : onOutOfMemoryError;
onOutOfMemoryError();
}
return emplace!(T, Args)(memory, args);
}
void deallocate(T)(T obj)
{
import core.stdc.stdlib : free;
destroy(obj);
free(cast(void*)obj);
}
void main()
{
auto test = allocate!C("YEAH!");
scope (exit) deallocate(test);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment