問(wèn)題描述
例如,假設(shè)我有一個(gè) Temp 類(lèi):
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;
};
當(dāng)我創(chuàng)建一個(gè) Temp 類(lèi)的對(duì)象時(shí),我將如何計(jì)算它需要多少空間,以及它在內(nèi)存中的表示方式(例如 | foobar 的 4 個(gè)字節(jié)| function1 的 8 個(gè)字節(jié) | 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 | )
推薦答案
對(duì)于一階近似,對(duì)象的大小是其組成數(shù)據(jù)成員的大小之和.您可以確定它永遠(yuǎn)不會(huì)比這更小.
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.
更準(zhǔn)確地說(shuō),編譯器有權(quán)在數(shù)據(jù)成員之間插入填充空間,以確保每個(gè)數(shù)據(jù)成員都滿(mǎn)足平臺(tái)的對(duì)齊要求.一些平臺(tái)對(duì)對(duì)齊非常嚴(yán)格,而其他平臺(tái) (x86) 更寬容,但在正確對(duì)齊的情況下會(huì)表現(xiàn)得更好.因此,即使是編譯器優(yōu)化設(shè)置也會(huì)影響對(duì)象大小.
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.
繼承和虛函數(shù)增加了額外的復(fù)雜性.正如其他人所說(shuō),您的類(lèi)的成員函數(shù)本身并不占用每個(gè)對(duì)象"的空間,但是該類(lèi)接口中虛函數(shù)的存在通常意味著存在一個(gè)虛表,本質(zhì)上是一個(gè)用于查找函數(shù)指針的表動(dòng)態(tài)解析正確的函數(shù)實(shí)現(xiàn)以在運(yùn)行時(shí)調(diào)用.虛擬表(vtbl)通常通過(guò)存儲(chǔ)在每個(gè)對(duì)象中的指針訪問(wèn).
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.
派生類(lèi)對(duì)象還包括其基類(lèi)的所有數(shù)據(jù)成員.
Derived class objects also include all data members of their base classes.
最后,訪問(wèn)說(shuō)明符(公共的、私有的、受保護(hù)的)在數(shù)據(jù)成員的打包方面為編譯器提供了一定的余地.
Finally, access specifiers (public, private, protected) grant the compiler certain leeway with packing of data members.
簡(jiǎn)短的回答是 sizeof(myObj) 或 sizeof(MyClass) 總是會(huì)告訴您對(duì)象的正確大小,但其結(jié)果并不總是容易預(yù)測(cè).
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.
這篇關(guān)于在 C++ 中如何確定對(duì)象的大小?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!