简体   繁体   中英

Why doesn't a reference to an array work until we use a pointer?

This works very well...

int a[5] = {1,2,3,4,5}, int *p = a;
int *& ref = p;

But why doesn't this work?

int a[5] = {1,2,3,4,5};
int*& ref = a;

Both a and p are pointers and have the same value (address of a[0] ). When I make reference to an array using a pointer ( p ), it works very well.

But when I make reference to that array a[] directly, it doesn't work... Why?

a is not a pointer, it is an array. It has the type int[5] . What it can do is decay to a pointer int* , which is what happens in the first case. So, taking a reference to p is ok.

Now for the second case. Remember that a is not a pointer. So, there is an implicit conversion happening from int[5] to int* . The result of that conversion is a prvalue. But you can't bind a non-const lvalue reference (which is what ref is) to an rvalue! So the code fails to compile.

Here's an analogy:

double a = 1.4;
int& b = a; // implicit conversion from 'double' to `int` results in prvalue
            // and you can't bind non-const lvalue refs to rvalues.

Adding on to what has already been answered, you can get a reference to an array like

int a[5];
int (&ref)[5] = a;

Live

int*& ref = a;

int* is a pointer type, not an array type. So, that's why it won't bind to a , which has type int[5] .

So, use const

int* const& ref = a;

It's works fine, Because the array name is an address constant, non-const reference can not refer to a constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM