Last active
August 29, 2015 14:13
-
-
Save aldanor/d5fb5e45ddf3dd2cb642 to your computer and use it in GitHub Desktop.
refcounted class proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.typecons; | |
import std.stdio; | |
import std.string; | |
import std.conv; | |
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() { | |
writeln("_Box!(", _instance, ").~this()"); | |
destroy(_instance); | |
} | |
} | |
RefCounted!(_Box!T) _payload; | |
} | |
~this() { | |
writeln("Box!(", _payload, ").~this()"); | |
} | |
auto opDispatch(string name, Args...)(Args args) { | |
return mixin("_payload._instance.%s(args)".format(name)); | |
} | |
size_t refcount() const @property { | |
return _payload.refCountedStore.refCount; | |
} | |
string toString() const { | |
return to!string(_payload._instance); | |
} | |
} | |
class Test { | |
int x; | |
this(int x) { | |
this.x = x; | |
writeln("Test(", x, ").this()"); | |
} | |
~this() { | |
writeln("Test(", x, ").~this()"); | |
} | |
void foo(int y) { | |
writeln("Test(", x, ").foo()"); | |
} | |
int bar() const { | |
writeln("Test(", x, ").bar()"); | |
return x * 100; | |
} | |
override string toString() const { | |
return "Test(%d)".format(x); | |
} | |
} | |
void f1() { | |
writeln("---> f1"); | |
auto box = Box!Test(100); | |
writeln(box.refcount); | |
auto box2 = box; | |
writeln(box.refcount, " ", box2.refcount); | |
box.foo(10); | |
writeln(box2.bar); | |
writeln("<--- f1"); | |
} | |
void main() { | |
writeln("<<< before f1"); f1(); writeln(">>> after f1"); | |
} |
Author
aldanor
commented
Jan 13, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment