On Sunday, 4 October 2015 at 22:10:18 UTC, Namespace wrote:
On Sunday, 4 October 2015 at 20:18:25 UTC, rsw0x wrote:
On Sunday, 4 October 2015 at 18:02:21 UTC, bitwise wrote:
[...]

It's just a symptom of D classes being so difficult to use without the GC, compared to when I first picked up D to now I find myself barely *ever* using classes and just C-style(er, D-style?) polymorphism with structs, mixins, and alias this.
Bye.

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();
}
----

And if I want to nest a class in a struct? or pass a class around? and still have deterministic destruction?

You can't nest a Scoped in a struct, and RefCounted doesn't work on a class.

It just shouldn't be this hard do such trivial things.

   Bit


Reply via email to