"The last feature": scope structs

dsimcha dsimcha at yahoo.com
Sun Feb 14 06:45:52 PST 2010


== Quote from bearophile (bearophileHUGS at lycos.com)'s article
> dsimcha:
> >Such a library construct should also allow strong class instances inline in
other class instances.<
> How can this be done? Is it possible to take any class and instantiate it with a
placement new inside another class instance? I'd like to see a bit of the
implementation code.
> Thank you, bye,
> bearophile

Here's a quick and dirty implementation.  I haven't thought about how to work out
all the details yet:

1.  If the class contains immutable members, this implementation allows for
overwriting immutable data.

2.  I don't know how to give the struct proper type information so that the GC
won't scan it if it doesn't contain any pointers.  Right now I'm using void[],
which needs to always be conservatively scanned.

3.  The way I handled c'tors isn't going to work with ref parameters, etc.

import std.stdio;

struct InlineClass(C) {
    enum instanceSize = __traits(classInstanceSize, C);
    void[instanceSize] space = void;

    this(T...)(T args) {
        space[] = typeid(C).init[];
        instance.__ctor(args);
    }

    C instance() {
        return cast(C) cast(void*) &this;
    }

    alias instance this;
}

class Foo {
    uint n;

    this(uint startVal) {
        n = startVal;
    }

    void printN() {
        writeln("Called printN for the ", n++, "th time.");
    }
}

void main() {
    auto foo = InlineClass!Foo(5);
    foo.printN();
    foo.printN();
}



More information about the Digitalmars-d mailing list