On Sunday, 4 October 2015 at 22:10:18 UTC, Namespace wrote:
You can use classes without GC _and_ with deteministic lifetime:

----
import std.stdio;

class A {
        string name;
        
        this(string name) {
                this.name = name;
        }
        
        void hello() {
                writeln("Hallo, ", this.name);
        }
}

struct Scoped(T) if (is(T == class)) {
        import core.stdc.stdlib : malloc, free;
        
        enum SIZE = __traits(classInstanceSize, T);
        
        T obj;
        
        this(Args...)(auto ref Args args) {
                void[] buffer = malloc(SIZE)[0 .. SIZE];
                buffer[] = typeid(T).init[];
                
                this.obj = cast(T) buffer.ptr;
                this.obj.__ctor(args);
        }
        
        ~this() {
                destroy(this.obj);
                free(cast(void*) this.obj);
        }
        
        alias obj this;
}

auto scoped(T, Args...)(auto ref Args args) if (is(T == class)) {
        return Scoped!T(args);
}

void main() {
        auto a = scoped!A("Foo");
        a.hello();
}
----

This can be shortened to:

import std.stdio;
import std.typecons;

class A
{
        string name;

        this(string name)
        {
                this.name = name;
        }

        void hello()
        {
                writeln("Hello, ", this.name);
        }
}

void main()
{
        auto a = scoped!A("Foo");
        a.hello();
}

Reply via email to