Destructor called while object is still alive

Steven Schveighoffer schveiguy at gmail.com
Fri Oct 23 19:39:52 UTC 2020


On 10/23/20 3:23 PM, frame wrote:
> On Friday, 23 October 2020 at 17:47:34 UTC, Steven Schveighoffer wrote:
>> On 10/23/20 12:48 PM, Ola Fosheim Grøstad wrote:
>>> On Friday, 23 October 2020 at 16:30:52 UTC, Steven Schveighoffer wrote:
>>>> No, D classes map to C++ pointers to classes.
> 
>> It doesn't have to even have a pointer if it's never used.
>> ...
>> The optimizer is wrong, and should be changed.
>>
>> Note that LDC does not do this optimization.
>>
> 
> So how can I avoid this issue with DMD? Disabling any optimization? In 
> fact it does not occur with debug mode enabled.

I don't know if you need to do that. As much discussion as this post has 
generated, and even though the optimization is wrong, the specific 
circumstances that could cause a piece of memory to be collected before 
it's used is really unlikely. To spell it out again:

1. You generate a GC block (i.e. new class)
2. You store it as part of an initializer for a stack local
3. You never use it in the stack frame
4. But you also in that same initialization put it into a location that 
is not scanned by the GC (e.g. C-malloc'd data)

If you aren't doing all 4 of these things, then you don't have to worry.

> Actually I do use the pointer in real code, (just one method call before 
> a loop but still used).
> 

So it shouldn't be collected then, even with optimizations.

-Steve


More information about the Digitalmars-d mailing list