Wednesday, January 26, 2011

Notes about "Inside The C++ Object Model"

Chapter 1 Object Lessons

1. All overhead on layout and memory access result from keyword "virtual":
  • invoking virtual function need run-time binding;
  • for virtual multi-inherited class, converting to 2nd or later base class will cost more operations.
2. C++ Object model:
  • nonstatic data members locates in the object space;
  • static data members lies outside all class objects;
  • nonvirtual function members lies out of all class objects;
  • in order to support virtual function, each class will maintain a virtual table (vtbl), and each class object will has a virtual table pointer (vptr), which points to corresponding virtual table.
3. An Object Distinction
  • C++ use the following ways to support polymorphism:
    • implicit type conversion, e.g. use base class pointer to refer a derived class object.
    • virtual functions
    • dynamic_cast and typeid
  • How to decide object size
    • sum size of all non-static member data
    • overhead from alignment
    • overhead from virtual function and virtual base class
  • Pointer type conversion doesn't change memory layout. Its only change is data type and size when compiler interpret memory.

chapter 2 The Semantics of Constructors
1. clear object space?
Global object memories are ensured to be reset to 0 when launch the program. However, local objects are in stack, and heap objects are in free space, which are not ensured to be reset to 0. Their content will be the data they were used last time.

2. Only 4 cases will create nontrivial default constructor. Otherwise objects without constructor will have an implicit trivial default function, which is actually not created.
  • Contains member class objects with default constructor;
  • Base class has a default constructor;
  • Has a virtual function
  • Has virtual base class(es).
The only reason compiler create a default constructor is to avoid itself creating object in a wrong way. If it is not necessary to have any construction operation, compiler will not create a default constructor.

3. Automatically created constructor only satisfy the compiler, not what the program want it to be! They will not give member data a default value!

4. There are 4 cases, in which compiler will create a non-bitwise copy constructor:

  1. Class contains any member object which has a copy constructor;
  2. Base class has a copy constructor;
  3. Class contains any virtual function, and are assigned to a base class object;
  4. Class has any virtual base class, and are assigned to a base class object.
The only reason compiler create a copy constructor is to avoid itself doing copy in a wrong way. If bitwise copy works in all possible situation for a class, compiler will not create a copy constructor.