C++各種類型的sizeof大小,先放測試代碼和測試結果(VS2013)。
#include
using namespace std;
////////// 測試基礎類型 //////////
int GetArraySize(char str[])
{
return sizeof(str);
}
void TestSizeofBase()
{
cout << "////////// 測試基礎類型 //////////" << endl;
char* pStr = "hello world";
char arrStr[] = "hello world";
cout << "char: " << sizeof(char) << endl;
cout << "short: " << sizeof(short) << endl;
cout << "int: " << sizeof(int) << endl;
cout << "float: " << sizeof(float) << endl;
cout << "double: " << sizeof(double) << endl;
cout << "char*: " << sizeof(pStr) << endl;
cout << "string: " << sizeof("hello world") << endl;
cout << "char[]: " << sizeof(arrStr) << endl;
cout << "char[] as param: " << sizeof(GetArraySize(arrStr)) << endl;
cout << endl;
}
//////////// 測試空類 ////////////
class EmptyA
{
};
class EmptyB : public EmptyA
{
};
struct EmptyStruct
{
};
void TestSizeofEmpty()
{
cout << "//////////// 測試空類 ////////////" << endl;
cout << "EmptyA: " << sizeof(EmptyA) << endl;
cout << "EmptyB: " << sizeof(EmptyB) << endl;
cout << "EmptyStruct: " << sizeof(EmptyStruct) << endl;
cout << endl;
}
////////// 測試內存對齊 //////////
class AlignA
{
char a;
};
class AlignB
{
char a;
short b;
};
class AlignC
{
char a;
short b;
double c;
};
#pragma pack(1)
class AlignD
{
char a;
short b;
double c;
};
#pragma pack()
void TestSizeofAlign()
{
cout << "////////// 測試內存對齊 //////////" << endl;
cout << "AlignA: " << sizeof(AlignA) << endl;
cout << "AlignB: " << sizeof(AlignB) << endl;
cout << "AlignC: " << sizeof(AlignC) << endl;
cout << "AlignD: " << sizeof(AlignD) << endl;
cout << endl;
}
//////////// 測試多態 ////////////
class VirtualA
{
virtual void test();
};
class VirtualB
{
virtual void test();
virtual void test2();
};
void VirtualB::test() {}
void VirtualB::test2() {}
class VirtualC
{
char a;
virtual void test();
virtual void test2();
};
void TestSizeofVirtual()
{
cout << "//////////// 測試多態 ////////////" << endl;
VirtualB objB;
cout << "VirtualA: " << sizeof(VirtualA) << endl;
cout << "VirtualB: " << sizeof(VirtualB) << endl;
cout << "VirtualB Object: " << sizeof(objB) << endl;
cout << "VirtualC: " << sizeof(VirtualC) << endl;
cout << endl;
}
void TestSizeof()
{
TestSizeofBase();
TestSizeofEmpty();
TestSizeofAlign();
TestSizeofVirtual();
}
int main(int argc, char **argv)
{
TestSizeof();
getchar();
return 0;
}
sizeof(GetArraySize(arrStr)) 4,是因為參數傳遞為形參時,把數組轉為了指針。
sizeof(空類) 1,是因為實例化類需要編譯器給它分配內存空間,不能分配為size為0的內存,所以編譯器默認分配了一個字節,以便標記可能初始化的類實例,同時使空類占用的空間也最少(即1字節)。
內存對齊,對象的首地址能夠被其最寬基本類型成員的大小所整除;每個成員相對於結構體首地址的偏移量(offset)都是成員大小的整數倍, 如有需要編譯器會在成員之間加上填充字節(internal adding);總大小為最寬基本類型成員大小的整數倍。
虛函數,虛函數表指針,大小相當於sizeof(void *)。