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

三世轮回 提交于 2019-12-21 07:04:07

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/40200807/why-is-the-conversion-from-char-to-charconst-invalid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!