Does C++ virtual function call on derived object go through vtable?

后端 未结 6 531
情书的邮戳
情书的邮戳 2020-12-11 17:13

In the following code, it calls a virtual function foo via a pointer to a derived object. Will this call go through the vtable or will it call B::foo directly?<

6条回答
  •  时光取名叫无心
    2020-12-11 17:53

    As usual, the answer to this question is "if it is important to you, take a look at the emitted code". This is what g++ produces with no optimisations selected:

    18     b->foo();
    0x401375 :  mov    eax,DWORD PTR [esp+28]
    0x401379 :  mov    eax,DWORD PTR [eax]
    0x40137b :  mov    edx,DWORD PTR [eax]
    0x40137d :  mov    eax,DWORD PTR [esp+28]
    0x401381 :  mov    DWORD PTR [esp],eax
    0x401384 :  call   edx
    

    which is using the vtable. A direct call, produced by code like:

    B b;
    b.foo();
    

    looks like this:

    0x401392 :  lea    eax,[esp+24]
    0x401396 :  mov    DWORD PTR [esp],eax
    0x401399 :  call   0x40b2d4 <_ZN1B3fooEv>
    

提交回复
热议问题