Idomatic way to guarantee to run destructor?
Robert M. Münch
robert.muench at saphirion.com
Sat May 2 08:44:00 UTC 2020
On 2020-04-30 17:45:24 +0000, Steven Schveighoffer said:
> 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.
Ok, that was my understand too. As said, I found some older posts and
was a bit confused...
> 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?
> 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...
> 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).
Ok, thanks.
--
Robert M. Münch
http://www.saphirion.com
smarter | better | faster
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20200502/0edc391a/attachment.htm>
More information about the Digitalmars-d-learn
mailing list