How do I call a context objects destructor or some type of exit() function automatically upon exiting a with {} scope?

Daniel Daniel
Tue Apr 1 23:00:32 UTC 2025


On Tuesday, 1 April 2025 at 17:08:27 UTC, Mike Parker wrote:
> On Tuesday, 1 April 2025 at 16:54:50 UTC, Daniel Donnelly, Jr. 
> wrote:
>> [...]
>
> You've used `new`, which means it's allocated with the GC. In 
> that case, your destructor is a finalizer and may or may not be 
> called at any point during the program. It's non-deterministic.
>
> If `Context` is a class, you can do this:
>
> ```
> scope ctx = new Context;
> ```
>
> This will allocate the class instance on the stack so the 
> destructor will be called when the scope exits. And of course, 
> if it's a struct, then just drop the new.
>
> All of that said, D does have scope guards when you need them:
>
> https://dlang.org/spec/statement.html#scope-guard-statement


Thank you, that makes sense!


More information about the Digitalmars-d-learn mailing list