Idomatic way to guarantee to run destructor?

Ben Jones fake at fake.fake
Thu Apr 30 17:04:43 UTC 2020


On Thursday, 30 April 2020 at 16:55:36 UTC, 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?


I think you want to use scope rather than auto which will put the 
class on the stack and call its destructor: 
https://dlang.org/spec/attribute.html#scope


More information about the Digitalmars-d-learn mailing list