Destructor called while object is still alive

Steven Schveighoffer schveiguy at gmail.com
Fri Oct 23 17:47:34 UTC 2020


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.
> 
> Huh? D has to be able to call virtual destructors for C++ objects.

And when are those called? When the lifetime of the *object* is over, 
not the lifetime of the pointer to the object.

My point was that C++ doesn't have class references, they have class 
pointers, which is akin to D class references.

> 
>> How does C++ RAII work for class pointers that aren't used?
> 
> What do you mean? The pointer is valid until the end of the scope. Then 
> the object is destructed if it is a sole owning pointer.

I mean, if I compile this code for C++, does it store the pointer on the 
stack?

void foo()
{
    SomeClass* ptr = new SomeClass();
    ... // bunch of other code that never uses ptr
}

C++ doesn't have automatic management using pointers. So the answer is, 
the optimizer might just not store `ptr`. Just like it doesn't happen in D.

> 
> _all_ GC pointers are conceptually owning pointers. They have to stay 
> live throughout the whole scope.

It doesn't have to even have a pointer if it's never used.

However, even though this case isn't "bad", there are bad cases that can 
be a problem:

auto c = storeWithC(new C);

If the function is something that squirrels away the parameter into a 
C-malloc'd block or C global (basically anything that is not scanned by 
the GC), and then returns the parameter, c is still not allocated on the 
stack, and the GC might collect it.

If DMD isn't smart enough to see that the reference may have escaped, 
then it shouldn't elide storage.

Under this view, I think actually the OP's case is a problem. Because 
Bar.create() could potentially be saving the result into a C heap block, 
in which case eliding the pointer storage is potentially going to cause 
memory corruption.

The optimizer is wrong, and should be changed.

Note that LDC does not do this optimization.

-Steve


More information about the Digitalmars-d mailing list