Skip to content

Instantly share code, notes, and snippets.

@aldanor
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aldanor/d5fb5e45ddf3dd2cb642 to your computer and use it in GitHub Desktop.
Save aldanor/d5fb5e45ddf3dd2cb642 to your computer and use it in GitHub Desktop.
refcounted class proxy
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");
}
@aldanor
Copy link
Author

aldanor commented Jan 13, 2015

$ rdmd test.d
<<< before f1
---> f1
Test(100).this()
1
2 2
Test(100).foo()
Test(100).bar()
10000
<--- f1
Box!(RefCounted!(_Box!(Test), cast(RefCountedAutoInitialize)1)(RefCountedStore(68B850))).~this()
Box!(RefCounted!(_Box!(Test), cast(RefCountedAutoInitialize)1)(RefCountedStore(68B850))).~this()
_Box!(Test(100)).~this()
Test(100).~this()
>>> after f1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment