Allocating a class within another class during object init w/o passing in an allocator

visitor via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 15 11:08:56 PST 2016


On Thursday, 15 December 2016 at 17:44:23 UTC, David  Zhang wrote:
> 

would something like this be a solution ?

import std.stdio;
import std.experimental.allocator;

class SomeClass {
     int someint = 42;

     static SomeClass opCall(int a) {
         auto inst = theAllocator.make!SomeClass;
         inst.someint += a;
         return inst;
     }

     void destruct() {
         theAllocator.dispose(this);
     }
}

class Foo {
     this() {
         sc = SomeClass(7);
         sc.someint -= 42;
     }

     ~this() {
         sc.destruct();
     }

     size_t something;
     SomeClass sc;
}



void main(string[] args) {
     auto foo = theAllocator.make!Foo;
     assert(foo.sc.someint == 7);
     theAllocator.dispose(foo);
}



More information about the Digitalmars-d-learn mailing list