Idomatic way to guarantee to run destructor?

Steven Schveighoffer schveiguy at
Thu Apr 30 17:45:24 UTC 2020

On 4/30/20 12:55 PM, Robert M. Münch wrote:
> For ressource management I mostly use this pattern, to ensure the 
> destructor is run:
> void myfunc(){
>   MyClass X = new MyClass(); scope(exit) X.destroy;
> }
> I somewhere read, this would work too:
> void myfunc(){
>   auto MyClass X = new MyClass();
> }
> What does this "auto" does here? Wouldn't
> void myfunc(){
>   auto X = new MyClass();
> }
> be sufficient? And would this construct guarantee that the destructor is 
> run? And if, why does "auto" has this effect, while just using "new" 
> doesn't guarantee to run the destructor?

No, auto is declaring that there's about to be a variable here. In 
actuality, auto does nothing in the first case, it just means local 
variable. But without the type name, the type is inferred (i.e. your 
second example). This does not do any automatic destruction of your 
class, it's still left to the GC.

You can use scope instead of auto, and it will then allocate the class 
on the stack, and destroy it as Ben Jones said. There is danger there, 
however, as it's very easy to store a class reference elsewhere, and 
then you have a dangling pointer.

A safer thing to do is:

auto X = new MyClass();
scope(exit) destroy(X);

This runs the destructor and makes the class instance unusable, but does 
not free the memory (so any remaining references, if used, will not 
corrupt memory).

If your concern is guaranteeing destructors are run, that's what I would 
pick. If in addition you want guaranteed memory cleanup, then use scope 
(and be careful).


More information about the Digitalmars-d-learn mailing list