重溫《Inside The C++ Object Model》(1),insidethegirls

來源:互聯網
上載者:User

重溫《Inside The C++ Object Model》(1),insidethegirls

C/C++ 編程風格

//1.C風格(結構化程式設計):資料和函數(操作)沒有任何關聯性typedef struct Point3d{    float x;    float y;    float z;} Point3d_t;voidPoint3d_print(const Point3d_t *pd){    printf("%g, %g, %g\n", pd->x, pd->y, pd->z);}

//2.基於對象(Object-Base):提供抽象資料類型(ADT)來支援封裝class Point3d{    friend ostream &operator<<(ostream &os, const Point3d &pt);public:    Point3d(float x = 0.0, float y = 0.0, float z = 0.0):        _x(x), _y(y), _z(z) {}    float x()    {        return _x;    }    float y()    {        return _y;    }    float z()    {        return _z;    }    void x(float xval)    {        _x = xval;    }    //etc...private:    float _x;    float _y;    float _z;};inline ostream &operator<<(ostream &os, const Point3d &pt){    return os << "( " << pt._x << ", " << pt._y << ", "           << pt._z << " )";}

//3.物件導向(Object-Oriented-Model):提供繼承和多態class Point{public:    Point(float x = 0.0):        _x(x) {}    float x()    {        return _x;    }    void x(float xValue)    {        _x = xValue;    }protected:    float _x;};class Point2d : public Point{public:    Point2d(float x = 0.0, float y = 0.0):        Point(x), _y(y) {}    float y()    {        return _y;    }    void y(float yValue)    {        _y = yValue;    }protected:    float _y;};class Point3d : public Point2d{    friend inline ostream &    operator<<(ostream &os, const Point3d &pt);public:    Point3d(float x = 0.0, float y = 0.0, float z = 0.0):        Point2d(x, y), _z(z) {}    float z()    {        return _z;    }    void z(float zValue)    {        _z = zValue;    }private:    float _z;};inline ostream &operator<<(ostream &os, const Point3d &pt){    return os << "( " << pt._x << ", " << pt._y << ", "           << pt._z << " )";}

//4.面向泛型:提供模板提供類型無關化的編程風格//樣本(1):僅提供型別參數化template <typename Type>class Point3d{public:    Point3d(Type x = 0.0, Type y = 0.0, Type z = 0.0):        _x(x), _y(y), _z(z) {}    Type x()    {        return _x;    }    Type y()    {        return _y;    }    Type z()    {        return _z;    }    void x(const Type &xval)    {        _x = xval;    }    //etc...private:    Type _x;    Type _y;    Type _z;};

//樣本(2):同時提供類型和數目(int dim)參數化template <typename Type, int dim>class Point{public:    Point() {}    Point(Type coordes[dim])    {        for (int index = 0; index < dim; ++index)        {            _coordes[index] = coordes[index];        }    }    const Type &operator[](int index) const    {        assert(index < dim && index >= 0);        return _coordes[index];    }private:    Type _coordes[dim];};template <typename Type, int dim>inline ostream &operator<<(ostream &os, const Point< Type, dim > &pt){    os << "( ";    for (int i = 0; i < dim; ++i)        os << pt[i] << ", ";    os << ")";    return os;}//測試    int array[] = {11,12,333};    Point<int, 3> point(array);    cout << point << endl;cout << point[2] << endl;

小結:C++加上封裝的布局成本

(1)三個data-member[資料成員]直接內含在每一個class-object[對象]之中,如同C-Struct一樣;

(2)Member-function雖然存在於class的聲明中, 卻不出現在object之中, 每一個non-inline member function[非inline的成員函數]只會誕生一個函數實體;

(3)而inline member function會在其每一個使用者身上產生一個函數實體.

 

C++物件模型

1.所有的資料成員(static 資料成員除外)存放在每一個對象之中;

2.[1]static 資料成員,[2]成員函數(無論是static/non-static)存放在所有對象之外;

3.對virtual-functions, 每一個對象都有一個vptr(指向一個vtbl(包含type_info object, virtual functions)).



因此:記憶體中對象的大小

(1)其non-static data member 的總和大小

(2)加上任何alignment(記憶體對其)的需求而填補上去的空間[可能存在於members中間, 也可能存在於集合體邊界];

(3)加上支援virtual[vptr]而由內部產生的任何額外負擔.

//測試class Point1{};class Point2{private:    int number;};class Point3{public:    Point3(int _number = 0): number(_number) {}    ~Point3() {}    static void showCount()    {        std::cout << "Point3_count = " << Point3_count << std::endl;    }private:    static int Point3_count;private:    int number;};class Point4{public:    virtual ~Point4();private:    int number;};int main(){    cout << sizeof(Point1) << endl;    cout << sizeof(Point2) << endl;    cout << sizeof(Point3) << endl;    cout << sizeof(Point4) << endl;}

對象在記憶體中的布局

Derived Class 的Object 和 Pointer布局(如)


(其實ZooAnimal subobject 的布局有些錯誤, string類型在現代C++中只佔4個位元組, 因此ZooAnimal subobject所佔的記憶體空間僅有12位元組, 而不是圖中的16位元組)

說明:

(1)pointer & reference 都只需一個字長(x86_32中為4個位元組)的空間;

(2)衍生類別對象中:基類子物件與衍生類別子物件在記憶體中的位置是相鄰的.

//測試class ZooAnimal{public:    ZooAnimal() {}    virtual ~ZooAnimal() {}    virtual void rotate() {}protected:    int loc;    string name;};class Bear : public ZooAnimal{public:    Bear() {}    ~Bear() {}    void rotate()    {    }protected:    enum Dances    {        //...    };    Dances dances_known;    int cell_block;};int main(){    Bear b;    ZooAnimal *pz = &b;    Bear *pb = &b;    cout << "Pointer..." << endl;    cout << sizeof(pz) << endl;    cout << sizeof(pb) << endl;    cout << "\nObject..." << endl;    cout << sizeof(*pz) << endl;    cout << sizeof(*pb) << endl;    cout << "\nClass..." << endl;    cout << sizeof(ZooAnimal) << endl;    cout << sizeof(Bear) << endl;}

測試說明:

pb 所涵蓋的地址包含了整個Bear Object, 而 pz只包含了Bear Object中的ZooAnimal SubObject!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.