sizeof operator
获取对象或类型的大小,以byte为单位。只有对象的确切大小可以被知道时才能使用。
返回值类型为std::size_t
语法
sizeof( type ) (1)
sizeof expression (2)
解释
(1)返回类型的对象表示的字节大小
(2)返回表达式返回类型的对象表示的字节大小
注意事项
根据计算机的类型不同,一个byte的bit数可能不同,精确数字参照CHAT_BIT
当应用到类类型时,其结果是该类对象的大小,以及将该对象置于数组中所需的任何额外填充
当应用到一个空的类时,sizeof总是返回1
当sizeof运算符用于引用,结果和sizeof应用到对象本身一样
sizeof的常见用法是sizeof array / sizeof array[0]
当应用到表达式时,表达式不会被计算
示例
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;
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' // error
// << "size of incomplete type: " << sizeof(int[]) << '\n' // error
// << "size of bit field: " << sizeof bit.bit << '\n' // error
<< "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
程序中带注释的三行是不能使用sizeof的情况,还有一些不能使用sizeof的情况如下:
Functions. (However,sizeof can be applied to pointers to functions.)
Bit fields.
Undefined classes.
The type void.
Dynamically allocated arrays.
External arrays.
Incomplete types.
Parenthesized names of incomplete types.