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

前端 未结 5 1031
借酒劲吻你
借酒劲吻你 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:05

    The C++11 draft standard explains this in a note in section 4.4 which says:

    [ Note: if a program could assign a pointer of type T** to a pointer of type const T** (that is, if line #1 below were allowed), a program could inadvertently modify a const object (as it is done on line #2). For example,

    int main() {
    const char c = 'c';
    char* pc;
    const char** pcc = &pc; // #1: not allowed
    *pcc = &c;
    *pc = 'C'; // #2: modifies a const object
    }
    

    —end note ]

    An interesting related question is Given int **p1 and const int **p2 is p1 == p2 well formed?.

    Note the C++ FAQ also has an explanation for this but I like the explanation from the standard better.

    The conforming text that goes with the note is as follows:

    A conversion can add cv-qualifiers at levels other than the first in multi-level pointers, subject to the following rules:56

    Two pointer types T1 and T2 are similar if there exists a type T and integer n > 0 such that:

    T1 is cv1,0 pointer to cv1,1 pointer to · · · cv1,n−1 pointer to cv1,n T

    and

    T2 is cv2,0 pointer to cv2,1 pointer to · · · cv2,n−1 pointer to cv2,n T

    where each cvi,j is const, volatile, const volatile, or nothing. The n-tuple of cv-qualifiers after the first in a pointer type, e.g., cv1,1, cv1,2, · · · , cv1,n in the pointer type T1, is called the cv-qualification signature of the pointer type. An expression of type T1 can be converted to type T2 if and only if the following conditions are satisfied:

    • the pointer types are similar.
    • for every j > 0, if const is in cv1,j then const is in cv2,j , and similarly for volatile.
    • if the cv1,j and cv2,j are different, then const is in every cv2,k for 0 < k < j.

提交回复
热议问题