On Thursday, 7 September 2017 at 23:40:11 UTC, Jiyan wrote:
Hey,
wanted to know whether it is possible to make anonymous nogc classes:

interface I
{
        public void ap();
}
void exec(I i)
{
        i.ap;
}

// now execute, but with something like `scope`
exec( new  class  I
{
        int tr = 43;
        override void ap(){tr.writeln;}
});

Thanks :)

Sadly, even std.typecons.scoped isn't currently @nogc:
https://issues.dlang.org/show_bug.cgi?id=13972
https://issues.dlang.org/show_bug.cgi?id=17592

This can be worked around by casting scoped's destructor to be @nogc, but that's a heavy-handed approach that ruins type safety, and is the wrong solution in non-@nogc situations. Should you want to, this is what it should look like:

        ~this()
        {
            (cast(void delegate(T) @nogc)((T t){
// `destroy` will also write .init but we have no functions in druntime // for deterministic finalization and memory releasing for now.
                .destroy(t);
            }))(Scoped_payload);
        }

If and when this issue is resolved, this should work:

interface I {
    public void ap();
}

void exec(I i) {
    i.ap;
}

auto scopedAnon(T)(lazy T dummy) if (is(T == class)) {
    import std.typecons;
    return scoped!T();
}

unittest {
    auto i = scopedAnon(new class I {
        int tr = 43;
        override void ap() {
            import std.stdio;
            tr.writeln;
        }
    });
    exec(i);
}

--
  Biotronic

Reply via email to