2

I am well aware of the const pointer to pointer problem, and I thought I knew what was going on, but boy I was wrong. I want to achieve this:

int* var[4];
const int* const (&refArray)[4] = var;      //compile error

Yes, I want to preserve the array instead of converting to pointer, and yes I actually met this problem in my code. So I went on to investigate what I can and cannot do, before long I realize I have no idea what's going on:

int* var[4];

const int* const * ptr = var;                     //allowed
const int* const * (&refPtr_indirect) = ptr;      //allowed

const int* const * (&refPtr) = var;               //error

const int* const * const (&constRefPtr) = var;    //allowed

int* const (&refArray)[4] = var;                  //allowed

const int* const (&refArray)[4] = var;            //error

I can understand the first four, but the last two makes absolutely no sense to me. I do see that the third version may work and that I can drop the reference, but I really hope to preserve the array type.

Any help is appreciated, but hopefully it can include the reasoning behind why the rules are as it is.

Community
  • 1
  • 1
Passer By
  • 19,325
  • 6
  • 49
  • 96

2 Answers2

1

You have an array of four pointers to (non-constant) int. To treat this as an array of four pointers to const int, you'd need to do a type pun. The types int [4] and const int [4] are different, a reference to one cannot refer to the other.

The best you could do is take a constant reference to the entire array. In complex situations like this, it's best to use some type names for manageability:

typedef int* TheArray[4];
TheArray var;
const TheArray &ref = var;

This gives you this:

ref[0];  // OK
ref[0] = nullptr;  // error
*ref[0];  // OK
*ref[0] = 42;  // OK

Your fifth version is the same, just without type names

int * const (&refArray) [4] = var;

A reference to a constant array of four pointers to int. (A constant array is the same as an array of constant elements).

The sixth version cannot possibly work, as I've said at the top—the types of the array elements are different, so no reference can refer to them both.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
0

Angew got some points, but I think the problem is that:

You can't convert int*[n] to const int*[n].

So this is allowed:

int a[4];
const int (&b)[4] = a;

But the following is not:

int *c[4];
const int *(&d)[4] = c;
Asu
  • 75
  • 4