Does the C++ language allow the following code to print e.g. 1 instead of 16? According to other answers I would guess yes but this case specifically doesn't seem to have been covered.
#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;
}
The Standard says under [dcl.ref]:
It is unspecified whether or not a reference requires storage
Also it is up to the compiler to decide what the size of an object is, so you could get any non-zero number here.
There is also the as-if rule (aka. permission to optimize). So it would be legal for the compiler to use storage for these references if and only if the way the references were used required it.
Having said all that; in the interests of having a stable ABI I would still expect that a compiler assigns storage to these references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With