Destructor called while object is still alive
Steven Schveighoffer
schveiguy at gmail.com
Fri Oct 23 16:00:58 UTC 2020
On 10/23/20 2:57 AM, Ola Fosheim Grøstad wrote:
> On Friday, 23 October 2020 at 06:37:43 UTC, Daniel Kozak wrote:
>> On Fri, Oct 23, 2020 at 8:20 AM frame via Digitalmars-d <
>> digitalmars-d at puremagic.com> wrote:
>>
>>> Even this is a "intelligent"
>>> feature by the compiler for non reachable code like that loop,
>>> it's still confusing. There are maybe situations while the object
>>> should stay in background, eg. socket related/event stuff. If
>>> there is a valid pointer, there is no excuse to reap it.
>>>
>>>
>> There is no use of foo anywhere so there is no reason to not collect it.
>
> It is in use until the end of main. Think locking. Seems like the
> pointer is optimized away and then the GC collects. Makes RAII useless
> with GC.
But you don't get RAII with classes or pointers. Only with structs.
>
> Basically a consequence of the optimizer assuming that there is no GC. A
> rather serious correctness issue.
>
>
I don't think so. A class reference itself doesn't have a destructor.
The compiler is free to elide storage just like it was a pointer. One
cannot expect any specific behavior from the GC in this case, as the
correctness of the program doesn't depend on the object staying in place
for the duration of the function. Here there is just a disconnect in how
the OP expects the compiler to implement the machine code.
Use a type that *does* support RAII (i.e. struct with dtor), and it will
be allocated and properly destroyed.
-Steve
More information about the Digitalmars-d
mailing list