Deep understanding of the C + + object model

Source: Internet
Author: User

C + + object model is an important point of knowledge, learning the memory model of C + + object, we can understand the polymorphism principle in C + +, the class initialization order problem, the class size problem and so on.

1 C + + object Model Foundation 1.1 What's in C + + objects

The C + + object includes the following:

    • Static constants
    • Member variables
    • member functions
    • Virtual functions
    • Pure continuation function
    • ...

The following is the definition of an object:

classbase{Static intb_s; Public:    voidfunction () {}Virtual voidv_function () {cout<<"Base v_function ()"<<Endl; }Private:    intb_a; intB_b;};
1.2 How large is a C + + object

If the base class is used as a test, how many bytes does the base class occupy in memory?

WINDOW7 vs2013 Test Results:

CENTOS7 64-bit VIM test results:

Based on the above two test result graph analysis, the memory size of a class is determined by the following members:

    • The sum size of its non-static members
    • Plus any space to fill up (padding) due to the need for alignment
      • If there are only non-static members in the class, such as Char C; Then its size is 1.
      • If except char C, there is an int a; Then its size is 8
    • Plus the extra burden from within to support virtual
1.3 Some important grammatical sugars in C + +
    • Static constant integer member (double is not possible) to initialize directly within class
    • Static members can only be initialized outside of the class and are not static when initialized
    • The base class is enough to call the virtual function in the constructor actually calls the virtual function in the base class (this is different from Java)
    • Const member function: Do not modify class member data

2 C + + Object memory layout

The test code is as follows:

#include <iostream>using namespacestd;classbase{Static intb_s; Public:    voidfunction () {}Virtual voidv_function () {cout<<"Base v_function ()"<<Endl; }    intb_a; intB_b;};intbase::b_s =0;intMainintargcChar**argv) {BaseBase; Base. b_a =1; Base. B_b =2; cout<<"Size:"<<sizeof(Base) <<Endl; int*p = (int*) &Base; cout<< *p <<Endl; P++; cout<< *p <<Endl; P++; cout<< *p <<Endl; System ("Pause"); return 0;}

The output is:

The outputs of 1 and 2 are the values of the b_a and B_b members in the class, 11459700 representing an address, and the address containing the information for the virtual table. The approximate memory layout of the base class is as follows:

2.1 What is the size of an empty class?
class Empty {}; int Main (intChar * *argv) {    empty empty;    Empty emptys[ten];     sizeof (empty) << Endl;     sizeof (emptys) << Endl;    System ("pause");     return 0 ;}

The output is:

There is nothing in an empty class, but a variable (instance) of an empty class type is defined, each instance has a unique address in memory, and for this purpose, the compiler tends to add a byte implicitly to an empty class so that the empty class has a unique address in memory after instantiation.

2.2 Class initialization Relationship under C + + object inheritance System

(1) class initialization sequence from the perspective of space

Base class initialization – Subclass class initialization

(2) Order of class initialization from aerial view

base class static member – Subclass static Member – base class member variable – base class constructor – Subclass member Variable – subclass constructor

(3) Stand on the ground to see the class initialization sequence

base class static member – Subclass static member – (set v_ptr/base class member variable) – base class constructor – (set v_ptr/child class member variable) – subclass constructor

3 Virtual Table 3.1 virtual table pointer and virtual table structure in C + + class
    1. There is a virtual table pointer in a class that points to the corresponding virtual table, a class will have only one virtual table, each virtual table has more than one "slot", and each slot holds the address of a virtual function.
    2. The contents of the slot can be overwritten, and if the subclass overrides the virtual function in the parent class, the data in the corresponding position in the slot is overwritten.
    3. A virtual table holds a virtual function address, whether the virtual function is public or private.

3.2 Virtual tables under multiple inheritance

Virtual functions are supported in multiple inheritance, with the complexity of the second and subsequent base classes, and the "this pointer must be adjusted at execution time".

classBase1 { Public: Base1 (); Virtual~Base1 (); Virtual voidspeakclearly (); VirtualBase1 *clone ()Const;protected:    floatdata_base1;};classBase2 { Public: Base2 (); Virtual~Base2 (); Virtual voidNumber (); VirtualBase2 *clone ()Const;protected:    floatData_base2;};classDerived: PublicBASE1, PublicBase2 { Public: Derived (); Virtual~Derived (); VirtualDerived *clone ()Const;protected:    floatdata_derived;};

3.3 Virtual table structure under dummy inheritance

For what is virtual inheritance click: Virtual Inheritance-Baidu encyclopedia.

classpoint2d { Public: point2d (float=0.0,float=0.0); Virtual~point2d (); Virtual voidmumble (); Virtual floatZ (); //. . Other codeprotected:    float_x, _y;};classPoint3D:Virtual  Publicpoint2d { Public: Point3D (float=0.0,float=0.0,float=0.0); ~Point3D (); floatz ();protected:    float_z;};

3.4 Virtual Table pointers when to assign values
#include <iostream>using namespacestd;classbase{ Public: Base () {cout<<"Base ()"<<Endl;        Show (); int*p = &b; cout<<"base::b:"<< P <<Endl; P--; cout<<"base::vptr:"<< *p <<Endl; cout<<"*base::vptr:"<< * (int*) *p <<Endl; cout<<Endl; }    Virtual voidShow () {cout<<"base::show ()"<<Endl; } Public:    intb;};classDerived: Publicbase{ Public: Derived () {cout<<"Derived ()"<<Endl;        Show (); int*p = &b; cout<<"derived::b:"<< P <<Endl; P--; cout<<"derived::vptr:"<< *p <<Endl; cout<<"*derived::vptr:"<< * (int*) *p <<Endl; cout<<Endl; }    Virtual voidShow () {cout<<"derived::show ()"<<Endl; }Private:    intD;};intMainintargcChar**argv) {BaseBase;    Derived Derived; System ("Pause"); return 0;}

The output is:

From the output results, it can be concluded that the virtual table pointer is assigned 2 times during the construction process. Initialize as follows:

base class static member – Subclass static member – (set v_ptr/base class member variable) – base class constructor – (set v_ptr/child class member variable) – subclass constructor

Reference:

1. "Deep Exploration of C + + object Model"

2.C + + Empty class instance size is not 0 reason

Deep understanding of the C + + object model

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.