extern(C++) classes; dtor must go in vtable

Steven Schveighoffer schveiguy at yahoo.com
Tue May 22 13:37:44 UTC 2018


On 5/22/18 12:57 AM, Manu wrote:
> On 21 May 2018 at 15:39, Steven Schveighoffer via Digitalmars-d
> <digitalmars-d at puremagic.com> wrote:
>> On 5/21/18 6:26 PM, Manu wrote:
>>>
>>> On 21 May 2018 at 14:53, Jonathan M Davis via Digitalmars-d
>>> <digitalmars-d at puremagic.com> wrote:
>>>>
>>>> On Monday, May 21, 2018 14:33:44 Manu via Digitalmars-d wrote:
>>>>>
>>>>> How do virtual destructors work in normal D classes?
>>>>
>>>>
>>>> It is my understanding that destructors in D are never virtual but rather
>>>> that the runtime handles calling them correctly.
>>>
>>>
>>> Can someone please elaborate on this?
>>> I want to know exactly what this means in practise.
>>>
>>
>> What he means by never virtual is *ALWAYS* virtual ;) At least in the sense
>> of virtual C++ destructors, not ordinary virtual functions.
>>
>> Here is what the runtime does:
>>
>> https://github.com/dlang/druntime/blob/38d784a8acd9cfe6ff4dadac6883a40f392f7353/src/rt/lifetime.d#L1380
>>
>> In essence, each classinfo has it's "local" destructor,
> 
> Oooooohhh! It's in the classinfo (and not in the vtable!).
> I knew that actually, I have run into that code, I just forgot!

It's in the classinfo, but so is the vtable. It's not really any 
different, except the "slot" for the destructor is not in the vtable 
array, it's just a separate member. See here: 
https://github.com/dlang/druntime/blob/38d784a8acd9cfe6ff4dadac6883a40f392f7353/src/object.d#L957

> Okay, so it's not directly in the vtable, it's special-case... (it's
> actually an additional indirection over C++ to reach the dtor)

Not sure how C++ works. I think it's an extra indirection for any 
virtual function in D, since D only stores the classinfo pointer. In 
fact, the destructor is one less indirection, because it's not in an array.

> Proper extern(C++) handling will need to take that same function and
> jam it in the first slot of the C++ vtable instead, but it should be
> functionally identical I think.

I don't know if that's true. The destructor itself does NOT call the 
base class destructor automatically. That's why the machinery in 
lifetime.d exists. It's actually, come to think about it, a LOT of 
indirections (2 per class in the hierarchy).

It all depends on how C++ implements virtual destructors.

...Rereading...

Oh wait, you mean jam the *lifetime* function in the slot? Yeah, that 
would probably work.

-Steve


More information about the Digitalmars-d mailing list