Advertisement
Guest User

Untitled

a guest
Apr 26th, 2011
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.06 KB | None | 0 0
  1. /*
  2.  * (C) 2011 Daniel G., do whatever you want with this code but please note
  3.  * that it's just a simple example
  4.  */
  5. import std.stdio;
  6. import std.conv;
  7. import core.stdc.stdlib;
  8.  
  9. class Foo {
  10.     int x;
  11.     this(int x) {
  12.         writefln("Foo's constructor called");
  13.         this.x = x;
  14.     }
  15.     ~this() {
  16.         writefln("Foo's destructor called");
  17.     }
  18. }  
  19.  
  20. T myNew(T, Args...) (Args args) {
  21.     // get class size of class object in bytes
  22.     size_t clSize = __traits(classInstanceSize, T);
  23.     // allocate memory for the object
  24.     void* tmp = core.stdc.stdlib.malloc( clSize );
  25.     if(!tmp)
  26.         throw new Exception("no memory");
  27.     // splice it to become a void[]
  28.     void[] objMem = tmp[0..clSize];
  29.     // use std.conv.emplace to put Object into that memory
  30.     T ret = emplace!(T, Args)(objMem, args);
  31.     return ret; // return new custom allocated Object
  32. }
  33.  
  34. void myDelete(T)(T obj) {
  35.     clear(obj); // so destructor is called
  36.     // free memory of the object
  37.     core.stdc.stdlib.free(cast(void*)obj);
  38. }
  39.    
  40. void main() {
  41.     Foo f = myNew!Foo(42);
  42.     writefln("f.x = %s", f.x);
  43.     myDelete(f);
  44.     writefln("bye.");
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement