bind const T(&ref)[N] to an object of type T[N]


Ryan Haining

I've noticed strange semantics when binding references to pointers and arrays that differ in terms of constness to point and array elements, respectively. With pointers, this fails predictably:

int* p{};
const int*& p_ref{p};

non-const lvalue reference to type 'const int *' cannot bind to a  value of unrelated type 'int *'

Makes sense, pointer-to-int and pointer-to-const-int are two different types, adding a constbefore &allowing the compiler to generate a temporary file that works, but doesn't change the above.

However, what I think should be similar to an array is not

int arr[5]{};
const int (&arr_ref)[5]{arr};

Both clang and gcc compile the above without complaint, but why? I bind a non-const reference const int[5]to an object of type int[5]. Why is this allowed?

Update: Stephen C. Dewhurst describes a similar problem in Gotcha #32 (page 82) in C++ Gotchas

Benjamin Lindley

In your first example, if you allow this, you risk breaking the correctness of const.

int *p{};
const int*& p_ref{p}; // pretend this is okay
const int x = 10;
p_ref = &x;           // storing the address of a const int in a const int*, okay
*p = 5;               // Should be okay, because p is int*, not const int*,
                      // but oops, just modified a const value

References to arrays don't have this problem, because you can't point an array somewhere else (because it's not a pointer).

Pointer points have a similar problem. Typically, we store non-constant addresses Tin const T*. Because this works, people tend to think that it should be possible to store the address T*of a in a const T**. But this causes the same problem as the reference example above:

int* p;
const int** pp = &p;  // forbidden, but pretend it's okay for now
const int x = 10;
*pp = &x;              // storing the address of a const int in a const int*, okay
*p = 5;                // oops, modified a const int

Related


Bind ListView to List<T> or List<InterfaceOfT> with object type

username Following this question , I finally have a full List where Value has types like ushort , ulong, etc. However, when I bind it to a ListView and add items, I get "blank" rows. In other words, the ListView confirms that there are items, but doesn't displ

How to data bind an object of type String[]?

Grant Park I already know that it is possible to set the type for many other lists, but String[]in particular, I currently have to set the type to, Objectand then convert it to String[]. Use String&#91;&#93;will also not be accepted. E.g <data> <va

How to data bind an object of type String[]?

Grant Park I already know that it is possible to set the type for many other lists, but String[]in particular, I currently have to set the type to, Objectand then convert it to String[]. Use String&#91;&#93;will also not be accepted. E.g <data> <va