C语言是否允许以下代码打印,例如1而不是16?根据其他答案,我猜是的,但这个案例似乎没有被覆盖.
#include "iostream"
#include "cstdlib"
using namespace std;
struct as_array {
double &a,&b;
as_array(double& A,double& B)
: a(A),b(B) {}
double& operator[](const int i) {
switch (i) {
case 0:
return this->a;
break;
case 1:
return this->b;
break;
default:
abort();
}
}
};
int main() {
cout << sizeof(as_array) << endl;
}
解决方法
标准在[dcl.ref]下说:
It is unspecified whether or not a reference requires storage
此外,由编译器决定对象的大小,因此您可以在此处获得任何非零数字.
还有as-if规则(也称为优化权限).因此,当且仅当使用引用的方式需要时,编译器才能将存储用于这些引用是合法的.
说了这么多;为了获得稳定的ABI,我仍然希望编译器为这些引用分配存储.