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

前端 未结 5 1097
借酒劲吻你
借酒劲吻你 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条回答
  •  萌比男神i
    2020-11-22 11:32

    There are two rules here to note:

    • There are no implicit casts between T* and U* if T and U are different types.
    • You can cast T* to T const * implicitly. ("pointer to T" can be cast to "pointer to const T"). In C++ if T is also pointer then this rule can be applied to it as well (chaining).

    So for example:

    char** means: pointer to pointer to char.

    And const char** means: pointer to pointer to const char.

    Since pointer to char and pointer to const char are different types that don't differ only in const-ness, so the cast is not allowed. The correct type to cast to should be const pointer to char.

    So to remain const correct, you must add the const keyword starting from the rightmost asterisk.

    So char** can be cast to char * const * and can be cast to const char * const * too.

    This chaining is C++ only. In C this chaining doesn't work, so in that language you cannot cast more than one levels of pointers const correctly.

提交回复
热议问题