GC: memory collected but destructors not called

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 14 07:44:59 PST 2014


On 11/14/14 6:25 AM, Rainer Schuetze wrote:
>
>
> On 11.11.2014 21:41, Steven Schveighoffer wrote:
>> In other words, putting a struct in the GC heap that was written to be
>> scope-destroyed is an error before and after this pull. Before the pull,
>> the dtor doesn't run, which is wrong, and after the pull the dtor may
>> cause race issues, which is wrong. So either way, it's wrong :)
>
> I think if someone uses "new" to allocate a struct on the GC heap, he
> must be aware of the consequences of using the GC. What happens within
> destruction/finalization is just the same as if it had been wrapped in a
> class, and that's what everyone(?) expects.

The issue I have is, how do you enforce that as the author of the struct?

Basically, I think you have 2 situations with struct dtors:
1. the struct author intends a struct to strictly be used on the stack 
(or on some other heap, such as C heap), and never expects to be GC 
destructed.
2. the struct author allows it to be GC stored, and faces the 
consequences of that.

Even with these 2 options, allowing GC storage precludes certain things. 
For example, the RefCounted struct goes through great pains to ensure 
its payload is NOT on the GC heap, because the dtor will not work if the 
payload is GC based (it may be already deallocated). The issues are so 
numerous and hairy, that option 2 should really only be left to "experts."

I think we need a better story for GC-stored structs than just letting 
people do it.

All this being said, having the GC perform what it is supposed to is 
also good. Bottom line -- I think the pull is the right thing to do 
(clearly, not calling dtors in some cases is not correct), but the 
problems are not all solved. We need to continue working on this until 
it's quite simple to make a struct that behaves correctly no matter 
where you put it.

-Steve


More information about the Digitalmars-d mailing list