2015年3月30日星期一

Memory Allocation and Vtable

1. There are four members in C++: static data member, non-static data member, static member function and non-static member function.
2. There are mainly five kinds of memory allocation:
(1) stack: created by program, and deallocated by program. Usually, function parameter, local variable and return value in this part.
(2) heap: no predetermined memory size. Programmers apply some sizes of memory and manually released the memory when not need it, or when program ends, the memory was reclaimed automatically.
(3)global and static(.bss): for global and static variable.
(4) literal constant(.data): for const string.
(5)code(.text):executable code.









3. non-static data member is put inside each object as its exclusive data. Static data member, static member function and non-static member function are all extracted into static data area and shared by all the objects. So only one copy is allowed. Only data belongs to one object and non-static data is binded by "this" pointer with the object. Each member function is shared by all the objects to perform the same actions but operator this data members.
4. Virtual table(V-Table)
(1) Single inheritance
In memory, first, there is a virtual table pointer vtbl, then data from base class and after this, data from the derived class. The vtbl points to the virtual table in which there are the addresses of all the virtual functions terminated with NULL. If the function in the derived class overrides the function in the baseclass, the function in the derived class replaces the function in base class.

In this diagram, v2 in class B overrides v2 in class A, v1 in class C overrides v1 in the class A and v3 in class C overrides v3 in Class B.
So, the memory module likes this.

(2) Multiple inheritance
Like single inheritance, all the virtual functions are in the virtual table, but for multiple inheritance, there are many virtual tables. If the function in the derived class overrides the function in base class, the virtual function in the derived class replaces the one in base class in the virtual table, but if new function created in the derived class, this function will be added into the virtual table.

In this diagram, v3 in class D overrides v3 in class B, a new function created in Class D.
So, the memory module likes this.

(3) virtual inheritance
There is only one base class in virtual inheritance. Compared to multiple inheritance, vbtable is added to store the offset to the base class.

In this diagram, vB in class D2 overrides vB in class B, class GD overrides vD1 in class D1 and meanwhile vB in Class B. new function created in Class GD.
So, the memory module likes this.
Now, there we go!

没有评论:

发表评论