Why are arrays of references illegal?


The following code does not compile.

int a = 1, b = 2, c = 3;
int& arr[] = {a,b,c,8};

What does the C++ standard say about this?

I know I could declare a class that contains a reference, then create an array of that class, as shown below. But I really want to know why the code above doesn't compile.

struct cintref
    cintref(const int & ref) : ref(ref) {}
    operator const int &() { return ref; }
    const int & ref;
    void operator=(const cintref &);

int main() 
  int a=1,b=2,c=3;
  //typedef const int &  cintref;
  cintref arr[] = {a,b,c,8};

It is possible to use struct cintref instead of const int & to simulate an array of references.

8/21/2016 9:32:37 PM

Accepted Answer

Answering to your question about standard I can cite the C++ Standard §8.3.2/4:

There shall be no references to references, no arrays of references, and no pointers to references.

12/6/2017 9:29:46 AM

References are not objects. They don't have storage of their own, they just reference existing objects. For this reason it doesn't make sense to have arrays of references.

If you want a light-weight object that references another object then you can use a pointer. You will only be able to use a struct with a reference member as objects in arrays if you provide explicit initialization for all the reference members for all struct instances. References cannot be default initalized.

Edit: As jia3ep notes, in the standard section on declarations there is an explicit prohibition on arrays of references.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow