查询对象或类型的大小

在需要知道对象的实际大小时使用。

语法

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 起)

关键词

sizeof

示例

本示例的输出对应于具有 64 位指针和 32 位 int 的系统。

运行此代码

  1. #include <iostream>
  2.  
  3. struct Empty {};
  4. struct Base { int a; };
  5. struct Derived : Base { int b; };
  6. struct Bit { unsigned bit: 1; };
  7.  
  8. int main()
  9. {
  10. Empty e;
  11. Derived d;
  12. Base& b = d;
  13. [[maybe_unused]] Bit bit;
  14. int a[10];
  15. std::cout << "size of empty class: " << sizeof e << "\n"
  16. << "size of pointer: " << sizeof &e << "\n"
  17. // << "size of function: " << sizeof(void()) << "\n" // 错误
  18. // << "size of incomplete type: " << sizeof(int[]) << "\n" // 错误
  19. // << "size of bit field: " << sizeof bit.bit << "\n" // 错误
  20. << "size of array of 10 int: " << sizeof(int[10]) << "\n"
  21. << "size of array of 10 int (2): " << sizeof a << "\n"
  22. << "length of array of 10 int: " << ((sizeof a) / (sizeof *a)) << "\n"
  23. << "length of array of 10 int (2): " << ((sizeof a) / (sizeof a[0])) << "\n"
  24. << "size of the Derived: " << sizeof d << "\n"
  25. << "size of the Derived through Base: " << sizeof b << "\n";
  26.  
  27. }

可能的输出:

  1. size of empty class: 1
  2. size of pointer: 8
  3. size of array of 10 int: 40
  4. size of array of 10 int (2): 40
  5. length of array of 10 int: 10
  6. length of array of 10 int (2): 10
  7. size of the Derived: 8
  8. size of the Derived through Base: 4