Cleanup class after method?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Jul 4 16:02:25 UTC 2018


On Wednesday, July 04, 2018 15:47:25 JN via Digitalmars-d-learn wrote:
> Imagine I have a very short-lived class:
>
> void print(File f)
> {
>      PrinterManager pm = new PrinterManager();
>      pm.print(f);
> }
>
> My understanding is that PrinterManager will be GC allocated, and
> when it goes out of scope, the GC will possibly clean it up at
> some point in the future. But I know that this class won't be
> used anywhere, I want to clean it up right now so that GC doesn't
> waste time later. In C++ it'd be handled by RAII, pm would be a
> unique_ptr<PrinterManager>. How to do it in D?

The typical thing to do in that case is to use a struct, not a class, since
structs have RAII, and they don't need to be allocated on the heap. However,
if you're stuck with a class, you can use scope. e.g.

scope pm = new PrintManager;

In that case, the class will actually be allocated on the stack instead.
However, I would point out that until -dip1000 becomes the normal behavior,
using scope like this is unsafe, because you have serious problems if any
reference to the class object escapes, since it's stack-allocated instead of
heap-allocated, and if any reference to it escapes, then it's referring to
an invalid object. If you're careful, it's fine, but it is a risk, and
regardless, using a struct is preferable if it's possible.

-dip1000 fully implements scope so that it verifies that no reference
escapes, but it's not ready yet, let alone the default behavior.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list