c ++ vtable the virtual function table

1. Role:

Address for the object pointer has virtual functions, which should be performed to determine the actual function during operation


2. Memory layout:

Head position memory (64), i.e., 8 bytes at the beginning of the memory contents of the address value vtable

Vtable function while sequentially storing address values ​​(64-bit order of the array)


3. The code calls:

#include <stdio.h>

#include <iostream>

class P { 

 public:
    virtual void test() {std::cout << "test " << std::endl;}
    virtual void testa() {std::cout << "testa " << std::endl;}

 private:
    int a;
    
};

class S : public P { 
 public:
    void test() {std::cout << "test s" << std::endl;}
    void testc() {std::cout << "test s c" << std::endl;} 

 private:
    int c;
};
int main() {
    P *p = new S();
    void *ptr = (void*)(*((long*)p));
    printf("%x\n", ptr);

    void (*fun)(void) = (void(*)(void))(*((long*)ptr));
    printf("%x\n", fun);
    (fun)();
    delete p;

    return 0;
}
void * ptr = (void *) (* ((long *) p)); the address obtained vtable

void (* fun) (void) = (void (*) (void)) (* ((long *) ptr)); Get function pointer


Note:

1. Only those with virtual object class will have a vtable, for non-virtual function call can be specified directly in the compiler, without the need for additional action to get


case:

Why generally requires the destructor virtual;

Let P S is the parent class, then default code generated destructor will automatically include the S code to call the parent class destructor,

This can be explained when using S s; like local variable, which is capable of processed own destructor then automatically call the parent class destructor (constructor on the contrary), i.e., the code has been analyzed in subclass structure function,

However, when using P * p = new S (); time, if not virtual destructor of p, then the destructor ~ P will only function because, ~ P ​​() is not a virtual function, then no in the vtable which determines the call destructor,

During the compilation will be based on the type of P, ~ P's call direct only

Then when ~ P as virtual time, ~ P ​​as a function of the vtable, which points when S () when it ~ P () is a function of the actual point ~ S (), and therefore able to complete destruction correct function is called.


Published 140 original articles · won praise 28 · views 180 000 +

Guess you like

Origin blog.csdn.net/qq_16097611/article/details/78932019