码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 中的对象布局

时间:2015-06-24 12:45:45      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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     typedef void (*pf_t)(void);
42     
43     pf_t pf;
44     p = static_cast<int *>((int *)&a);
45     pf = (pf_t)p;
46     
47     int *vptr = *(int **)&a;
48     int *vtable = (int *)*vptr;
49     pf = (pf_t )vtable[2];
50 
51     printf("address A::fun %p\n",pf);
52 
53     cout << "p:" << *p << endl;
54     p ++ ;
55     cout << "p:" << *p << endl;
56     p++;
57     cout << "p:" << *p << endl;
58     p++;
59     cout << "p:" << *p << endl;
60         
61     p++;
62     cout << "p:" << *p << endl;
63 
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

 

C++ 中的对象布局

标签:

原文地址:http://www.cnblogs.com/maniford/p/4597304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!