C++各种类型的sizeof大小,先放测试代码和测试结果(VS2013)。
#include <iostream>
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 *)。
原文地址:http://blog.csdn.net/ynnmnm/article/details/45826963