AFAIK sizeof不会将其操作数评估为C++.
例如
int x = 0;
sizeof(x += 1); // value of x is not changed
Run Code Online (Sandbox Code Playgroud)
但是,这是什么意思?
int arr[5];
sizeof(arr+0); // here array is converted to pointer
Run Code Online (Sandbox Code Playgroud)
为什么在这里应用数组算术?
(第5.3.3/4节)左值到右值(4.1),数组到指针(4.2)和函数到指针(4.3)标准转换不应用于sizeof的操作数.
Mar*_*ork 17
sizeof()运算符在编译时计算.表达式未被评估.它是计算表达式的类型(在编译时),然后由sizeof()使用.
所以在你的第一个:
sizeof( x += 1);
Run Code Online (Sandbox Code Playgroud)
x的类型是int.+ =运算符的结果仍然是int.所以sizeof()仍然是int的大小.
在这:
sizeof(arr+0);
Run Code Online (Sandbox Code Playgroud)
这里arr是一个数组,并且会返回数组的大小(如果它本身使用的话).但是运算符+使数组衰减成指针.数组上的+运算符和整数的结果是指针.所以这里sizeof()运算符将返回指针的大小.
(第5.3.3/4节)左值到右值(4.1),数组到指针(4.2)和函数到指针(4.3)标准转换不应用于sizeof的操作数.
这意味着:
std::cout << sizeof(arr);
// would print sizeof(int)* 5 (because there is no conversion)
// if sizeof() had behaved like a normal function there
// would have been a conversion but as you pointed out that
// does not apply.
Run Code Online (Sandbox Code Playgroud)
但在这里:
std::cout << sizeof(arr + 5);
// prints the sizeof(int*) because the result of the expression
// is a pointer type (int*)
Run Code Online (Sandbox Code Playgroud)
这就是为什么
int x[0];
int const xSize = sizeof(x)/sizeof(x[0]);
// This works correctly even though x[0] is technically
// not valid if used in a real expression (but is valid here).
Run Code Online (Sandbox Code Playgroud)
事实并非如此.在算术表达式中,数组名称会衰减为指针.这对于执行计算本身没有任何意义.的类型+是从类型其操作数推断出,在这种情况下指针和整数,得到相同的结果sizeof(int*).