Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * (C) 2011 Daniel G., do whatever you want with this code but please note
- * that it's just a simple example
- */
- import std.stdio;
- import std.conv;
- import core.stdc.stdlib;
- class Foo {
- int x;
- this(int x) {
- writefln("Foo's constructor called");
- this.x = x;
- }
- ~this() {
- writefln("Foo's destructor called");
- }
- }
- T myNew(T, Args...) (Args args) {
- // get class size of class object in bytes
- size_t clSize = __traits(classInstanceSize, T);
- // allocate memory for the object
- void* tmp = core.stdc.stdlib.malloc( clSize );
- if(!tmp)
- throw new Exception("no memory");
- // slice it to become a void[]
- void[] objMem = tmp[0..clSize];
- // use std.conv.emplace to put Object into that memory
- T ret = emplace!(T, Args)(objMem, args);
- return ret; // return new custom allocated Object
- }
- void myDelete(T)(ref T obj) {
- clear(obj); // so destructor is called
- // free memory of the object
- core.stdc.stdlib.free(cast(void*)obj);
- // shouldn't hurt, the object must not be used anymore anyway
- obj = null;
- }
- void main() {
- Foo f = myNew!Foo(42);
- writefln("f.x = %s", f.x);
- myDelete(f);
- assert(f is null); // yeah it's null.
- writefln("bye.");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement