class destruction
ponce via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Sep 9 01:15:33 PDT 2015
On Wednesday, 9 September 2015 at 07:19:58 UTC, Q wrote:
> Hi. I'm playing around with D for a while and I would like to
> switch. But here is one thing, I need an answer for. In the
> Docs is mentioned that it is not sure that the DTor of a class
> is called. But what if I have struct, which holds a C Handle
> which is destroyed as soon as the struct gets destroyed (more
> or less like a unique pointer) and I stick this struct into a
> class (because I strongly need polymorphism)?
Then you have to make sure the class destruction happens and not
rely on the GC.
> Can I be sure that the Handle is destroyed as soon as the class
> is destroyed?
I think that yes, struct members are destroyed. But you need to
make sure the class is destroyed.
> If so there are only two ways that come to mind:
> 1. the class holds only a pointer to the struct, which is
> unsafe since I must guarantee that the struct lives as long as
> the class
> 2. the class gets a close/finalize/destroy method (or is called
> with the built in destroy method), which is a absolute nogo,
> because it is absolutly sure that this can be forgotten.
> Besides, we live in 2015 and that is not C where I have to
> clean my code manually, so this option would be ridiculous :D
>
> I'm gratefull for any answers and ideas.
I'm using the manual method after much hair-pulling:
http://p0nce.github.io/d-idioms/#GC-proof-resource-class
It absolutely is worse than the C++ situation, however with the
above pattern leaks will be reported by the GC, which is a nice
consolation prize.
Alternatively, stick your class in Unique! / Refcounted! / scoped!
More information about the Digitalmars-d-learn
mailing list