Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module refcounting;
- import core.exception;
- import std.c.stdlib;
- __gshared Object lock;
- __gshared int[void*] refCounts;
- shared static this()
- {
- enum objSize = __traits(classInstanceSize, Object);
- void* memory = malloc(objSize);
- if (!memory)
- {
- throw new OutOfMemoryError;
- }
- lock = emplace!(Object)(memory[0..objSize]);
- }
- struct RefCountedObj(T)
- if (is(T == class))
- {
- private:
- T _val;
- public:
- alias _val this;
- static RefCountedObj!(T) create(Args...)(Args args)
- {
- RefCountedObj!(T) obj;
- obj._val = alloc!(T)(args);
- return obj;
- }
- this(this)
- {
- synchronized(lock)
- {
- ++refCounts[cast(void*)_val];
- }
- }
- ~this()
- {
- synchronized(lock)
- {
- int refCount = --refCounts[cast(void*)_val];
- if (refCount == 0)
- {
- _val.__dtor;
- free(cast(void*)_val);
- }
- }
- }
- void opAssign(T value)
- {
- if (cast(void*)value != cast(void*)_val)
- {
- synchronized(lock)
- {
- int refCount = --refCounts[cast(void*)_val];
- if (refCount == 0)
- {
- _val.__dtor;
- free(cast(void*)_val);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement