Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can storage for references inside a C++ class be optimized away?

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;
}
like image 632
user3493721 Avatar asked Jun 16 '15 05:06

user3493721


1 Answers

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.

like image 100
M.M Avatar answered Sep 30 '22 10:09

M.M