Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

According to N4606, 4.5 [conv.qual] paragraph 3 reads

A prvalue expression of type T1 can be converted to type T2 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, T2 must be pointer to / const pointer to / const pointer to / T. Isn't T2 sufficient just for being more cv-qualified than T1? Why are more cv-qualifiers in lower dimensions necessary for the conversion to succeed?

like image 309
b1sub Avatar asked Oct 23 '16 07:10

b1sub


People also ask

Can const char * Be Changed?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.

What is the difference between char and const char?

Simple: "char *name" name is a pointer to char, i.e. both can be change here. "const char *name" name is a pointer to const char i.e. pointer can change but not char.

What is the difference between const char * and string?

1 Answer. Show activity on this post. string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.

Why do we use const char?

If you don't have the choice, using const char* gives a guarantee to the user that you won't change his data especially if it was a string literal where modifying one is undefined behavior. Show activity on this post. By using const you're promising your user that you won't change the string being passed in.


1 Answers

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.

like image 86
celtschk Avatar answered Oct 19 '22 16:10

celtschk