您的位置:首页 > 编程语言 > C语言/C++

c++ 对象模型与内存结构

2017-03-21 18:50 411 查看

c++ Object model

object = data + algorithm

Data Layout

plain object

struct foo{
int a,b,c;
};


12bytes

alignment

struct foo{
short a;
int b;
short c;
};


short 2bytes

memory alignment 12bytes

inheritance

struct foo{
short a;
int b;
};
struct bar:foo{
short c;
//short d; also 12bytes
};


12bytes

4bytes alignment,foo 8bytes,c 4bytes

object in object

struct foo{
short a;
int b;
};
struct bar{
foo f;
short d;
};


12 bytes

static storage

layout : somewhere else

static member

functions

vtables

Virtual Binding

some conception

vtable:is the table containing address of Virtual Functions of each class.

vptr:is the vpointer,which points to the Virtual Function for that object

virtual binding:A point or reference to an object calls virtual function

static binding:

An object calls function

A pointer or reference to an object or the object itself calls any non-virtual function

important points to remember

Only the Base class Method’s declaration needs the Virtual Keyword, not the definition.

If a function is declared as virtual in the base class, it will be virtual in all its derived classes.

The address of the virtual Function is placed in the VTABLE and the copiler uses VPTR(vpointer) to point to the Virtual Function.

constuct order

Construct virtual base class(es)

Construct base class(es)

Construct vptr(s)

Construct objects not in initialization list

Construct objects in initialization list

Call constructor

note

vptr is replaced again and again down the hierarchy tree

Virtual function lose its virtuousness before the construction complete reguardless of static or dynamic binding

conclusion

the size of class’s memory

all the non-static member data

memory alignment

to support virtual function,it may need extra memory

Reference

c++ object model
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息