Il-seob Bae Il-seob Bae - 5 months ago 36
C++ Question

Why is the conversion from char*** to char*const** invalid?

According to the latest draft of the C++ standard (N4606) , 4.5 [conv.qual] paragraph 3 reads

A prvalue expression of type
can be converted to type
if the following conditions are satisfied, where cvij denotes the cv-qualifiers in the cv-qualification signature of Tj:

  • ...

  • If the cv1i and cv2i are different, then const is in every cv2k for 0 < k < i.

The final bullet above suggests that the following conversion fails.

T1 : pointer to / pointer to / pointer to / T
T2 : pointer to / pointer to / const pointer to / T

In order to succeed,
must be
pointer to / const pointer to / const pointer to / T
. Isn't
sufficient just for being more cv-qualified than
Why are more cv-qualifiers in lower dimensions necessary for the conversion to succeed?


Consider the following code:

char str[] = "p1 should always point here.";
char* const p1 = str;
char** p2 = nullptr;
char*** p3 = &p2;

char str2[] = "Can we make p1 point to here?"
// p1 = str2; // does not work: const violation

// But:
char*const** p4=p3; // if it were allowed
*p4 = &p1; // no const violation, as *p4 is of type char*const*
**p3 = str2; // oops, changed p1!

So if the conversion in question were allowed, you'd get to change a constant variable (p1) without any formal const violation.