C++关键字-sizeof
sizeof是一个单目运算符。
作用是返回一个对象或类型所占的内存字节数。
返回值类型为size_t
。(在头文件stddef.h中定义)
sizeof是一个编译时运算符,编译过程中就会计算出sizeof的具体值,然后用值替换掉sizeof (),所以它可以被当作常量表达式使用:
char arr[sizeof(int) * 10];
sizeof的语法形式:
sizeof (object); //sizeof(对象)
sizeof object; //sizeof 对象
sizeof (type_name); //sizeof(类型)
sizeof的用法
基本数据类型的sizeof
linux 64bit系统下:
bool | char | short | int | long | long long | float | double | long double | |
---|---|---|---|---|---|---|---|---|---|
sizeof | 1 | 1 | 2 | 4 | 8 | 8 | 4 | 8 | 16 |
注:不能对void
使用sizeof
指针的sizeof
任何指针类型的sizeof求值结构都是8(64bit系统),包括void*
指针变量的sizeof
值与指针所指的对象类型没有任何关系,与指针申请多少空间没有关系,所有的指针变量所占内存大小均相等。
数组类型的sizeof
当sizeof作用于数组时,求取的是数组所有元素所占用的大小。
当数组作为函数参数时,退化为指针,此时sizeof(数组)的结果为指针的size。
传入数组指针,并对指针解引用,得到的sizeof就是数组的size。
void foo1(int arr[6])
{
// 8,指针的size
cout << sizeof(arr) << endl;
// 4,首元素int的size
cout << sizeof(*arr) << endl;
}
void foo2(int (*arr)[6])
{
// 8,指针的size
cout << sizeof(arr) << endl;
// 24,数组的size
cout << sizeof(*arr) << endl;
}
int main()
{
int arr[6] = {};
// 24
cout << sizeof(arr) << endl;
foo1(arr);
foo2(&arr);
}
c-style字符串的sizeof
sizeof(字符串)会计算\0
的size
strlen(字符串)不会计算\0
的size
函数的sizeof
对函数使用sizeof,并不会调用函数,在编译阶段会被函数返回值的类型取代。
struct类型的sizeof
struct类型的sizeof需要考虑字节对齐。
类对象类型的sizeof
- 成员函数不占size。
- 如果存在虚函数,则sizeof的结果需要加上虚函数表指针的size。
- 派生类的sizeof结果需要加上基类的size。
容器的sizeof
像std::vector
,std::string
等容器,本质还是一个类,它们的sizeof求值结果为类的size,和容器储存的数据元素size无关。
但是std::array
是个例外。
int main()
{
std::vector<int> v1(1);
std::vector<int> v2(100);
cout << "element count: " <<v1.size() << " sizeof(v1): " << sizeof(v1) << endl;
cout << "element count: " <<v2.size() << " sizeof(v2): " << sizeof(v2) << endl;
std::string s1("hello");
std::string s2('h', 100);
cout << "element count: " <<s1.size() << " sizeof(s1): " << sizeof(s1) << endl;
cout << "element count: " <<s2.size() << " sizeof(s2): " << sizeof(s2) << endl;
std::array<int, 10> v1;
std::array<int, 100> v2;
cout << "element count: " <<v1.size() << " sizeof(v1): " << sizeof(v1) << endl;
cout << "element count: " <<v2.size() << " sizeof(v2): " << sizeof(v2) << endl;
}
输出:
element count: 1 sizeof(v1): 24
element count: 100 sizeof(v2): 24
element count: 5 sizeof(s1): 32
element count: 104 sizeof(s2): 32
element count: 10 sizeof(v1): 40
element count: 100 sizeof(v2): 400