問題描述
例如,假設我有一個 Temp 類:
For example, say I have a class Temp:
class Temp
{
public:
int function1(int foo) { return 1; }
void function2(int bar) { foobar = bar; }
private:
int foobar;
};
當我創建一個 Temp 類的對象時,我將如何計算它需要多少空間,以及它在內存中的表示方式(例如 | foobar 的 4 個字節| function1 的 8 個字節 | etc | )
When I create an object of class Temp, how would I calculate how much space it needs, and how is it represented in memory (e.g.| 4 bytes for foobar| 8 bytes for function1 | etc | )
推薦答案
對于一階近似,對象的大小是其組成數據成員的大小之和.您可以確定它永遠不會比這更小.
To a first order approximation, the size of an object is the sum of the sizes of its constituent data members. You can be sure it will never be smaller than this.
更準確地說,編譯器有權在數據成員之間插入填充空間,以確保每個數據成員都滿足平臺的對齊要求.一些平臺對對齊非常嚴格,而其他平臺 (x86) 更寬容,但在正確對齊的情況下會表現得更好.因此,即使是編譯器優化設置也會影響對象大小.
More precisely, the compiler is entitled to insert padding space between data members to ensure that each data member meets the alignment requirements of the platform. Some platforms are very strict about alignment, while others (x86) are more forgiving, but will perform significantly better with proper alignment. So, even the compiler optimization setting can affect the object size.
繼承和虛函數增加了額外的復雜性.正如其他人所說,您的類的成員函數本身并不占用每個對象"的空間,但是該類接口中虛函數的存在通常意味著存在一個虛表,本質上是一個用于查找函數指針的表動態解析正確的函數實現以在運行時調用.虛擬表(vtbl)通常通過存儲在每個對象中的指針訪問.
Inheritance and virtual functions add an additional complication. As others have said, the member functions of your class themselves do not take up "per object" space, but the existence of virtual functions in that class's interface generally implies the existence of a virtual table, essentially a lookup table of function pointers used to dynamically resolve the proper function implementation to call at runtime. The virtual table (vtbl) is accessed generally via a pointer stored in each object.
派生類對象還包括其基類的所有數據成員.
Derived class objects also include all data members of their base classes.
最后,訪問說明符(公共的、私有的、受保護的)在數據成員的打包方面為編譯器提供了一定的余地.
Finally, access specifiers (public, private, protected) grant the compiler certain leeway with packing of data members.
簡短的回答是 sizeof(myObj) 或 sizeof(MyClass) 總是會告訴您對象的正確大小,但其結果并不總是容易預測.
The short answer is that sizeof(myObj) or sizeof(MyClass) will always tell you the proper size of an object, but its result is not always easy to predict.
這篇關于在 C++ 中如何確定對象的大小?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!