Why can't vtable contain duplicate functions?

Imagine a project that has an interface class, such as:

struct Interface { virtual void f()=0; virtual void g()=0; virtual void h()=0; }; 

Suppose someone else wants to create a class that implements this interface, for which f , g , h all do the same.

 struct S : Interface { virtual void f() {} virtual void g() {f();} virtual void h() {f();} }; 

Then it would be a proper optimization to create a vtable for S whose entries are all pointers to S::f , thereby preserving the call of the wrapper functions g and h .

However, printing the contents of vtable indicates that this optimization is not being performed:

 S s; void **vtable = *(void***)(&s); /* I'm sorry. */ for (int i = 0; i < 3; i++) std::cout << vtable[i] << '\n'; 

0x400940
0x400950
0x400970

Compiling with -O3 or -Os no effect, nor does switching between clang and gcc.

Why is this optimization feature missing?

At the moment, these are the assumptions that I have considered (and rejected):

  • The vtable print code actually prints trash.
  • Improving performance is considered futile.
  • ABI forbids it.
+6
source share
1 answer

Such optimization is not valid because ...

 // somewhere-in-another-galaxy.hpp struct X : S { virtual void f(); }; // somewhere-in-another-galaxy.cpp include <iostream> void X::f() { std::cout << "Hi from a galaxy far, far away! "; } 

If the compiler implements your optimization, this code will not work.

 Interface* object = new X; object->g(); 

The compiler of my translation unit does not know about the internal implementation of your class, so for g () and h () it simply puts links to the virtual function tables of my class to the corresponding entries in your VFT class.

+2
source

All Articles