Object Layout in Memory

Object Layout in Memory

Preface

Teacher mentioned this in class, but I don’t understand at all about these stuff at that time.

So I read the Game Engine Architecture page 121 – 128, which helps me a lot. Here is the reading notes.

Rules

Put larger data type on the top in struct to fit the alignment. Add explicit padding to the end of the struct manually.

Alignment and Packing

When small data members are interspersed with larger members, it will leave “holes” in the layout.

inse

Many modern CPU can only read and write aligned block of data.Every data type has a natural alignment which must be respected in order to permit the CPU to read and write memory effectively.

Good to do

Re-arrange the members by putting largest member on the top.

Add explicit padding to the end of the struct manually, to make the wasted space visible and explicit.

e

It’s better to make the padding visible by manually add them to the end._pad[0] and _pad[1] will be add automatically by compiler in to struct anyway in order to guarantees all subsequent element in an array will be aligned properly.

Memory Layout of C++ Classes

Inheritance

v

When B inherits from class A, B’s data member simply appear immediately after A’s in memory.

Each new derived class tacks its data member on at the end.

Game programmer usually prefer to avoid multiple inheritance altogether.

Virtual functions

If a class contains or inherits one or more virtual functions, then four additional bytes are added to the class layout, typically at the very beginning of the class’ layout.

These four pointers are called the virtual table pointer or vpointer, because they contain a pointer to a data structure known as the virtual function table or vtable.

The vtable contains pointers to all the virtual functions that it declares or inherits. Every concrete class has its own virtual table, every instance of that class has a pointer to it, stored in its vpointer.

The heart of polymorphism

Example of a Circle class inherits the Shape class

Graph

graph

Code Example

 

class Shape
{
public:
   virtual void SetId(int id) { m_id = id; }
   int          GetId() const { return m_id;}
   virtual void Draw() = 0; //pure virtual - no impl.

privite:
   int m_id;
};

class Circle : public Shape
{
public:
   void     SetCenter (const Vector3& c) { m_center=c; }
   Vector3  GetCenter() const { return m_center; }
   void     SetRadius(float r) { m_radiuis = r; }
   float    GetRadius() const { return m_radius;}

   virtual void Draw()
   {
      // code to draw a circle
   }

private:
   vector3 m_center;
   float m_radius;
};

 

Jin Han

February 17, 2013

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.