Scoped Class Instance

Nicolas Silva nical.silva at gmail.com
Tue Jan 31 06:25:15 PST 2012


You can use structs for this kind of problems, somethin like

struct Scoped(T)
{
    ~this()
    {
        //handle deallocation here
    }
    T inst;
}

if you create a Scoped!MyClass in a scope, the struct's destructor
will be invoked whenever the program leaves the scope, even if it is
because of an exception.

On Tue, Jan 31, 2012 at 2:40 PM, Zachary Lund <admin at computerquip.com> wrote:
> 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