Why isn't it legal to convert “pointer to pointer to non-const” to a “pointer to pointer to const”

前端 未结 5 1030
借酒劲吻你
借酒劲吻你 2020-11-22 11:03

It is legal to convert a pointer-to-non-const to a pointer-to-const.

Then why isn\'t it legal to convert a pointer to pointer to non-const to a

5条回答
  •  粉色の甜心
    2020-11-22 11:07

    Ignoring your code and answering the principle of your question, see this entry from the comp.lang.c FAQ: Why can't I pass a char ** to a function which expects a const char **?

    The reason that you cannot assign a char ** value to a const char ** pointer is somewhat obscure. Given that the const qualifier exists at all, the compiler would like to help you keep your promises not to modify const values. That's why you can assign a char * to a const char *, but not the other way around: it's clearly safe to "add" const-ness to a simple pointer, but it would be dangerous to take it away. However, suppose you performed the following more complicated series of assignments:

    const char c = 'x';    /* 1 */
    char *p1;              /* 2 */
    const char **p2 = &p1; /* 3 */
    *p2 = &c;              /* 4 */
    *p1 = 'X';             /* 5 */
    

    In line 3, we assign a char ** to a const char **. (The compiler should complain.) In line 4, we assign a const char * to a const char *; this is clearly legal. In line 5, we modify what a char * points to--this is supposed to be legal. However, p1 ends up pointing to c, which is const. This came about in line 4, because *p2 was really p1. This was set up in line 3, which is an assignment of a form that is disallowed, and this is exactly why line 3 is disallowed.

    And as your question is tagged C++ and not C, it even explains what const qualifiers to use instead:

    (C++ has more complicated rules for assigning const-qualified pointers which let you make more kinds of assignments without incurring warnings, but still protect against inadvertent attempts to modify const values. C++ would still not allow assigning a char ** to a const char **, but it would let you get away with assigning a char ** to a const char * const *.)

提交回复
热议问题