Reuse object memory?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Apr 20 14:36:35 PDT 2015


On 04/20/2015 12:05 PM, Namespace wrote:

 > I'm sorry if I annoy you

Not at all! :) Sorry for not responding earlier.

 >, but I would really like to know how you would
 > reuse already instantiated storage of an existing object.
 >
 > Example code:
 > ----
 > final class Foo {
 >      uint id;
 >
 >      @nogc
 >      this(uint id) {
 >          this.id = id;
 >      }
 > }
 >
 > Foo f = new Foo(42);
 > ----

Something like the following works. I chose to set the old object to 
null but it is not necessary:

final class Foo {
     uint id;

     @nogc
     this(uint id) {
         this.id = id;
     }
}

C reuse(C, T...)(ref C old, T ctorParams)
{
     import std.conv;
     import std.typetuple;

     enum objectSize = __traits(classInstanceSize, C);

     void* oldPlace = cast(void*)old;
     C newObject = emplace!C(oldPlace[0..objectSize], ctorParams);

     old = null;

     return newObject;
}

void main()
{
     Foo f = new Foo(42);

     auto f2 = f.reuse(43);

     assert(f is null);
     assert(f2.id == 43);
}

Ali



More information about the Digitalmars-d-learn mailing list