Advertisement
Guest User

custom (de)allocation in D2 without new/delete

a guest
Jun 14th, 2011
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.18 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.     // slice 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)(ref T obj) {
  35.     clear(obj); // so destructor is called
  36.     // free memory of the object
  37.     core.stdc.stdlib.free(cast(void*)obj);
  38.     // shouldn't hurt, the object must not be used anymore anyway
  39.     obj = null;
  40. }
  41.    
  42. void main() {
  43.     Foo f = myNew!Foo(42);
  44.     writefln("f.x = %s", f.x);
  45.     myDelete(f);
  46.     assert(f is null); // yeah it's null.
  47.     writefln("bye.");
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement