On Tuesday, 13 January 2015 at 18:12:45 UTC, aldanor wrote:
On Tuesday, 13 January 2015 at 16:43:09 UTC, ketmar via Digitalmars-d-learn wrote:
On Tue, 13 Jan 2015 16:17:51 +0000
aldanor via Digitalmars-d-learn <digitalmars-d-learn@puremagic.com>
wrote:

This discussion: http://forum.dlang.org/thread/bqtcdpsopxmnfbjyr...@forum.dlang.org -- led me wondering if it would be possible to create some crippled version of a class proxy that is based on RefCounted and came up with something like this:

struct Box(T) if (is(T == class)) {
    @disable this();

    this(Args...)(Args args) {
        _payload._refCounted.initialize(new T(args));
    }

    private {
        struct _Box(T) {
            private T _instance;

            ~this() {
                destroy(_instance);
            }
        }
        RefCounted!(_Box!T) _payload;
    }

    ~this() {
    }

    auto opDispatch(string name, Args...)(Args args) {
return mixin("_payload._instance.%s(args)".format(name));
    }
}

which lets you create Box!SomeClass(args) and it will be refcounted unless you escape references and do other weird stuff.

It actually sort of seems to work at first glance, at least it seems like it does... But with my D experience being fairly limited I wonder what the potential pitfalls would be?

Full source code with example and stdout:
https://gist.github.com/aldanor/d5fb5e45ddf3dd2cb642
it's not that hard to make a boxed class. what is really hard is to make functions that expects the class itself to accept it's boxed
variant too and behave correctly with it.

either you have to unbox it (and then hope that it will not leak), or write two set of functions, for "real" class and for boxed one. and then you may want to inherit from your class and pass that inherited class to one of the functions... and now you have three sets. and so
on...

as structs can't be inherited, there is no such problem for structs.

That's completely valid. Where it would work though, I think, is if all classes are private/package and only expect/return boxed classes and never the references. This way you sort of get multiple inheritance (for the internal implementation) without polymorphism, but with value semantics and ref counting for the outward interface.
// thanks ketmar for answering another one of my stupid questions on n.g. :)

Reply via email to