C++ 中的对象布局

C++中的涉及到虚表时,类对象的布局分为:虚表与数据成员,子类包含派生类布局,假设下面一个程序:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 class B {
 6 private:
 7     int a;
 8 public:
 9     B() {
10         a = 11;
11     }
12 
13     virtual void fun() {
14         cout << "B::fun" << endl;
15     }
16 };
17 
18 class A:public B {
19 public:
20     A() {
21         cout << "class A constructor" << endl;        
22         m = 3;
23         n = 2;
24     }
25 
26     ~A() {
27         cout << "~A()" << endl;
28     }
29     virtual void fun() {
30         cout << "A::fun" << endl;
31     }
32 
33 private:
34     int m,n;
35 };
36 
37 int main(int argc, char *argv[])
38 {
39     A a;
40     int *p;
41     int **pvtr = (int **)&a;
42 
43     typedef void (*pf_t)();
44     
45     pf_t pf;
46     p = static_cast<int *>((int *)&a);
47 
48     pf = (pf_t)(pvtr[0][0]);
49     pf();
50     //cout << "*pf:" << *pf << ",pf:" << pf << endl;
51     
52     //(*(*pf+sizeof(void*) * 2))();
53 
54     cout << "p:" << *p << endl;
55     p ++ ;
56     cout << "p:" << *p << endl;
57     p++;
58     cout << "p:" << *p << endl;
59     p++;
60     cout << "p:" << *p << endl;
61         
62     p++;
63     cout << "p:" << *p << endl;
64 
65     return 0;
66 }

 

通过VS 2010显示对象布局图(cl -d1reportAllClassLayout),其中meta为对应对象的类型信息:

类B:

 1 class B    size(8):
 2     +---
 3  0    | {vfptr}
 4  4    | a
 5     +---
 6 
 7 B::$vftable@:
 8     | &B_meta
 9     |  0
10  0    | &B::fun

类A:

class A    size(16):
    +---
    | +--- (base class B)
 0    | | {vfptr}
 4    | | a
    | +---
 8    | m
12    | n
    +---

A::$vftable@:
    | &A_meta
    |  0
 0    | &A::fun

A::fun this adjustor: 0

 

posted on 2015-06-24 11:44  kkford  阅读(209)  评论(0编辑  收藏  举报

导航