Search code examples
c++arraysreference

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; }
private:
    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.


Solution

  • 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.

    That's because references are not objects and don't occupy the memory so don't have an address. You can think of them as the aliases to the objects. Declaring an array of nothing has not much sense.