Destructor called while object is still alive

Steven Schveighoffer schveiguy at gmail.com
Fri Oct 23 16:30:52 UTC 2020


On 10/23/20 12:14 PM, Ola Fosheim Grøstad wrote:
> On Friday, 23 October 2020 at 16:00:58 UTC, Steven Schveighoffer wrote:
>> But you don't get RAII with classes or pointers. Only with structs.
> 
> But that is only a consequence of the optimizer not being written with a 
> GC in mind. That is the point. Isn't D structs the same as C++ PODs? I 
> thought C++ classes with virtuals/RTTI is supposed to map to D classes? 
> Then RAII has to work.

No, D classes map to C++ pointers to classes.

How does C++ RAII work for class pointers that aren't used?

> 
>> 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.
> 
> That would be very surprising semantics as you expect a pointer to be 
> LIVE throughout the scope in which it was instantiated. If it is LIVE 
> then it cannot be collected by the GC.

Expectation for what purpose?

I think of code being executed in the way I write it. We all know that 
optimizers don't do that. As long as it's not changing the semantic 
meaning of the program, I'm fine with it.

If you look at this code:

void main()
{
    int i;
    foo();
}

Does i even exist? Does it exist after the first line? Is it important 
if the compiler allocates space for it on the stack? Does it get 
initialized to 0?

All of these things are items that have no bearing on the execution of 
the program, so it's fine for the optimizer to just completely get rid 
of the variable storage. This is no different.

> 
> This all boils down to the optimizer being GC ignorant. I understand 
> that it is too much work to make the optimizer take that into 
> consideration, but it most certainly goes against the expected norm for 
> the semantics of BLOCKS that LIVE pointers are being collected.
> 

I think the optimizer is correct. There are no live pointers, because 
the object is not used, ever.

How many times has someone posted code touting a benchmark of something 
and the optimizer gets rid of the entire program? How is this any different?

-Steve


More information about the Digitalmars-d mailing list