Why, really, deleting an incomplete type is undefined behaviour?

后端 未结 6 1728
北荒
北荒 2020-11-30 06:07

Consider this classic example used to explain what not to do with forward declarations:

//in Handle.h file
class Body;

class Handle
{
   public:
           


        
6条回答
  •  遥遥无期
    2020-11-30 06:11

    Calling a virtual method or a non-virtual method are two totally different things.

    If you call a non-virtual method, the compiler has to generate code that does this:

    • put all the arguments on the stack
    • call the function and tell the linker that it should resolve the call

    Since we're talking about the destructor, there are no arguments to put on the stack, so it looks like we can simply do the call and tell the linker to resolve the call. No prototype needed.

    However, calling a virtual method is totally different:

    • put all the arguments on the stack
    • get the vptr of the instance
    • get the n'th entry from the vtable
    • call the function to which this n'th entry points

    This is totally different so the compiler really has to know whether you are calling a virtual or non-virtual method.

    The second important thing is that the compiler needs to know on which position the virtual method is found in the vtable. For this, it also needs to have the full definition of the class.

提交回复
热议问题