Array type is not assigned

I need to create two references to an array that can refer to the same array. I tried the following:

extern int (&a)[];
extern int (&b)[];

int main()
{
    b = a; // error: array type 'int []' is not assignable
}

      

Is there a way to do this in C ++?

+3


source to share


1 answer


Two things: first, arrays cannot appear in the left hand of the assignment operator. cppreference probably takes text directly from the standard, in particular:

§ 8.3.4

5 Objects of array types cannot be modified, see 3.10.

Also, as cppreference says, arrays are lvalues:

§ 3.10

1 Expressions are classified according to the taxonomy in Figure 1. - An lvalue (so called historically, since lvalues ​​appear on the left side of an assignment expression) denotes a function or object.



Although the standard explicitly states that objects of array types cannot be modified, so the conclusion that arrays (which are objects) cannot appear on the left side of the assignment operator.

Second, although the compiler might not complain if you do this:

int a = 50, c = 42;
int& b = a;
b = c;
b = 80;
std::cout << a << " " << c; // 80 42

      

you will see what c

remains unchanged. Please refer to parashift C ++ - faq .

[8.5] ​​How can you re-establish a link to refer to another object?

In no case.

You cannot separate the link from the referent.

Unlike a pointer, when a reference is bound to an object, it cannot be "reset" to another object. The link itself is not an object (it has no ID, and the link address gives you the referrer's address; remember: the link is its referrer).

+5


source







All Articles