C++ typedef interpretation of const pointers

前端 未结 2 768
小蘑菇
小蘑菇 2020-11-29 06:50

Firstly, sample codes:

Case 1:


typedef char* CHARS;
typedef CHARS const CPTR;   // constant pointer to chars

Textually replacing C

2条回答
  •  被撕碎了的回忆
    2020-11-29 07:28

    There's no point in analyzing typedef behavior on the basis of textual replacement. Typedef-names are not macros, they are not replaced textually.

    As you noted yourself

    typedef CHARS const CPTR;
    

    is the same thing as

    typedef const CHARS CPTR;
    

    This is so for the very same reason why

    typedef const int CI;
    

    has the same meaning as

    typedef int const CI;
    

    Typedef-name don't define new types (only aliases to existing ones), but they are "atomic" in a sense that any qualifiers (like const) apply at the very top level, i.e. they apply to the entire type hidden behind the typedef-name. Once you defined a typedef-name, you can't "inject" a qualifier into it so that it would modify any deeper levels of the type.

提交回复
热议问题