Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c++ - Virtual Table layout in memory?

how are virtual tables stored in memory? their layout?

e.g.

class A{
    public:
         virtual void doSomeWork();
};

class B : public A{
    public:
         virtual void doSomeWork();
};

How will be the layout of virtual tables of class A and class B in memory?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For GCC compiler in Linux run:

g++ -fdump-class-hierarchy example.h

The output is:

Vtable for A
A::_ZTV1A: 3u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI1A)
16    (int (*)(...))A::doSomeWork

Class A
   size=8 align=8
   base size=8 base align=8
A (0x7fb76785a4e0) 0 nearly-empty
    vptr=((& A::_ZTV1A) + 16u)

Vtable for B
B::_ZTV1B: 3u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI1B)
16    (int (*)(...))B::doSomeWork

Class B
   size=8 align=8
   base size=8 base align=8
B (0x7fb7678510d0) 0 nearly-empty
    vptr=((& B::_ZTV1B) + 16u)
  A (0x7fb76785a540) 0 nearly-empty
      primary-for B (0x7fb7678510d0)

Also I've created the vtable-dumper tool to list contents of virtual tables in the shared objects. With this tool you don't need to compile headers, just run it on the object:

vtable-dumper SHLIB

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...