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

来源:互联网 发布:东华 数据库 编辑:程序博客网 时间:2024/06/15 00:45

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

0 0
原创粉丝点击