深度探索C++ 对象模型(1)-三种对象模型的设计
1.類的成員
- 數(shù)據(jù)成員
. Static
. Nonstatic - 成員函數(shù)
. Static
. Nonstatic
. virtual
Questions:
C++封裝帶來的布局成本是多大?
由空類組成的繼承層次中,每個類對象的大小是多大?(答案見此篇)
2.虛函數(shù)表
3.對象模型
// An highlighted block var foo = 'bar';class Point { public: Point( float xval ); virtual ~Point(); float x() const; static int PointCount(); protected: virtual ostream& print( ostream &os ) const;float _x; static int _point_count; };簡單對象模型
表格驅(qū)動對象模型
c++對象模型
附注:
RTTI(Run Time Type Identification)運行時類型識別
- 編譯器生成的特殊類型信息
- 包括對象繼承關系,對象本身的描述
- 為多態(tài)而生成的信息,所以只有具有虛函數(shù)的對象在會生成
三種對象模型比較
| 簡單對象模型 | 對象由一系列的指針組成,每一個指針都指向一個數(shù)據(jù)成員或成員函數(shù),也即是說,每個數(shù)據(jù)成員和成員函數(shù)在類中所占的大小是相同的 | 實現(xiàn)簡單 | 空間;執(zhí)行期的效率 |
| 表格驅(qū)動對象模型 | 一個指針指向數(shù)據(jù)成員表,一個指向函數(shù)表 | 如果應用程序代碼未曾改變,但所用的class objects的nonstatic data members有所修改,那么那些應用程序是否需要重新編譯有一定彈性,因為提供了一層間接性 | 空間;執(zhí)行期的效率 |
| C++對象模型 | 靜態(tài)數(shù)據(jù)成員,靜態(tài)成員函數(shù)和一般非靜態(tài)成員函數(shù)(包括構造函數(shù))均存放在class object之外(單獨存取,和對象無關),而非靜態(tài)數(shù)據(jù)成員則被放在每一個class object內(nèi),虛函數(shù)則由虛表支持 | 空間;執(zhí)行期的效率 | 如果應用程序代碼未曾改變,但所用的class objects的nonstatic data members有所修改,那么那些應用程序均得重新編譯 |
[2] 是對類的頭文件改變時,需要重新編譯的說明:
- add a data member
This changes the size of instances of the class. Might be Ok for anyone who just uses pointers or references, if you take care to put that data behind all other data, so that the offsets for accessing the other data members do not change. But the exact layout of sub objects in binary is not defined, so you will have to rely on a specific implementation.
【引用】
[1]: <<深度探索C++ 對象模型 Inside The C++ Object Model >> Stanley B.Lippman 候捷 譯
[2] C++ — When recompilation is required https://stackoverflow.com/questions/4033487/c-when-recompilation-is-required
總結
以上是生活随笔為你收集整理的深度探索C++ 对象模型(1)-三种对象模型的设计的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BigChainDB
- 下一篇: 深度探索C++ 对象模型(2)-类的对象