Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T* and const T*

I believe this may apply to many T's, but I know for sure this applies to integers. As part of learning C++, I am trying to explain the following behavior in terms of the language in the standard.

typedef const int * constintptr;
typedef int * intptr;

intptr p;
constintptr cp = p;
const constintptr& crcp = p;
//constintptr & rcp = p;

From looking at n3337, sec 8.5.3. It seems this behavior is explained by saying that int* is convertible to a const int * prvalue, but is not reference compatible. (correct me if I am wrong).

I see that this is desirable behavior (or we could subvert the const), and the desirability of this behavior is not what this question is about.

The question is where in the standard it is specified (or implied) that they intptr and constintptr are not reference-compatible.

like image 635
orm Avatar asked Mar 21 '23 03:03

orm


1 Answers

Same section, 8.5.3/4 (numbering from in n3797, which I have available) defines reference-compatible:

Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is reference-related to “cv2 T2” if T1 is the same type as T2 , or T1 is a base class of T2 . “cv1 T1” is reference-compatible with “cv2 T2” if T1 is reference-related to T2 and cv1 is the same cv-qualification as, or greater cv-qualification than, cv2

So you have type T1 is int* and T2 int const*. They are not the same type. Neither one of them is a base class of the other (because neither is a class at all). Therefore, they are not reference-related.

When the standard says "cv1 T1", it means any type that is a result of applying 0 or more of const, volatile to the type T1. It does not mean textual substitution, that is to say it does not mean any type that is declared by 0 or more of the keywords const, volatile followed by another sequence of tokens which is a type declaration for T1.

So it's possible that you've misunderstood this such that you think const int* is a cv-qualified version of int*. If it were, then under the general rule they would be reference-related and so there would need to be text in the standard to make an exception. But it is not. int *const is a cv-qualified version of int*.

like image 109
Steve Jessop Avatar answered Apr 02 '23 15:04

Steve Jessop