Idomatic way to guarantee to run destructor?

Steven Schveighoffer schveiguy at gmail.com
Sat May 2 18:18:44 UTC 2020


On 5/2/20 4:44 AM, Robert M. Münch wrote:
> On 2020-04-30 17:45:24 +0000, Steven Schveighoffer said:
> 
> 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.
> 
> 
> Ok. Can't this be combined with some "don't let the refrence escape my 
> function" feature of D?

I don't know. perhaps dip1000 helps here.

> 
> 
> 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).
> 
> 
> How would that help, because the class instance is now unusable anyway. 
> So I have it around like a zombie and others might think: "Hey you look 
> normal, let's get in contact" and then you are doomed...

The difference is that if you use it, you get an error and a crash. If 
you clean up the memory, that memory could be reallocated to something 
else with a completely different type, and now you have memory corruption.

-Steve


More information about the Digitalmars-d-learn mailing list