You can use scoped!() from std.typecons:

import std.stdio;
import std.typecons;

class A
{
    ~this()
    {
        writeln("A destructor");
    }
}

void foo()
{
    auto a1 = scoped!A();
}

void main()
{
    foo();
    writeln("exiting..");
}


You must not escape a reference to the object outside of the foo()
scope. Note that you will get a runtime error if you try to do
something like this:

import std.stdio;
import std.typecons;

class A
{
    ~this()
    {
        writeln("A destructor");
    }
}

auto foo()
{
    auto a1 = scoped!A();
    return a1;
}

void main()
{
    auto result = foo();
    writeln("exiting..");
}

Illegal call to Scoped this(this)
A destructor
core.exception.AssertError@std.typecons(2506): Assertion failure

Reply via email to