查询对象或类型的大小
在需要知道对象的实际大小时使用。
语法
sizeof( 类型 ) | (1) | |
sizeof 表达式
| (2) | |
两个版本都是 std::size_t 类型的常量表达式。
解释
1) 产生 类型 的对象表示的字节数。
2) 产生 表达式 的类型的对象表示的字节数,假如该表达式被求值。
注解
取决于计算机架构,字节可能具有八或更多位,精确的位数于 CHAR_BIT 记录。
sizeof(char)、sizeof(signed char)、sizeof(unsigned char) 和 sizeof(char8_t) 总是等于 1。
不能对函数类型、不完整类型或位域泛左值使用 sizeof
。
当应用于引用类型时,其结果是被引用类型的大小。
当应用于类类型时,其结果是该类的对象的大小加上这种对象放入数组时所需的额外填充的大小的和。
sizeof
的结果始终非零,即使应用于空类。
当应用于某个表达式时,sizeof
并不对表达式进行求值,并且即便表达式代表多态对象,其结果也是该表达式的静态类型的大小。不进行左值向右值、数组向指针和函数向指针转换。不过,它在形式上对纯右值实参进行临时量实质化:sizeof
确定其结果对象的大小。 (C++17 起)
关键词
示例
本示例的输出对应于具有 64 位指针和 32 位 int 的系统。
运行此代码
- #include <iostream>
- struct Empty {};
- struct Base { int a; };
- struct Derived : Base { int b; };
- struct Bit { unsigned bit: 1; };
- int main()
- {
- Empty e;
- Derived d;
- Base& b = d;
- [[maybe_unused]] Bit bit;
- int a[10];
- std::cout << "size of empty class: " << sizeof e << "\n"
- << "size of pointer: " << sizeof &e << "\n"
- // << "size of function: " << sizeof(void()) << "\n" // 错误
- // << "size of incomplete type: " << sizeof(int[]) << "\n" // 错误
- // << "size of bit field: " << sizeof bit.bit << "\n" // 错误
- << "size of array of 10 int: " << sizeof(int[10]) << "\n"
- << "size of array of 10 int (2): " << sizeof a << "\n"
- << "length of array of 10 int: " << ((sizeof a) / (sizeof *a)) << "\n"
- << "length of array of 10 int (2): " << ((sizeof a) / (sizeof a[0])) << "\n"
- << "size of the Derived: " << sizeof d << "\n"
- << "size of the Derived through Base: " << sizeof b << "\n";
- }
可能的输出:
- size of empty class: 1
- size of pointer: 8
- size of array of 10 int: 40
- size of array of 10 int (2): 40
- length of array of 10 int: 10
- length of array of 10 int (2): 10
- size of the Derived: 8
- size of the Derived through Base: 4
当前内容版权归 cppreference 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 cppreference .