Scoped Class Instance

Zachary Lund admin at computerquip.com
Tue Jan 31 05:40:47 PST 2012


I've been looking into (basic) memory management within D. Through IRC 
conversation and reading the article on memory management on dlang.org 
(which seems to be a bit out-of-date), I've concluded that using a 
global (or static member) function and emplace() in std.conv is a simple 
solution for providing alternative allocation methods. However, I 
cannot, by default, scope my custom allocations. Take this for instance:

void main() {
	MyClass inst = alloc!(MyClass)();
	inst.do_something();
	dealloc(inst);
}

Now, I want my dealloc function to be called automagically. One safe 
measure is:

void main() {
	MyClass inst = alloc!(MyClass)();
	scope(exit) dealloc(inst);
	inst.do_something();
}

But I'm lazy and I'm looking for shorter methods.

void main() {
	mixin AutoRef(MyClass, "inst");
	inst.do_something();
}

Any ideas?


More information about the Digitalmars-d-learn mailing list