New to C++. Question about constant pointers

前端 未结 10 1898
梦谈多话
梦谈多话 2021-02-10 06:55

I am trying to learn C++ via some web tutorials. I don\'t have a compiler available to me, otherwise I would try this out. I\'m not sure what is meant by a const pointer. Doe

10条回答
  •  暖寄归人
    2021-02-10 07:08

    As it has already been pointed out the perhaps most common const pointer is

    const char* p;
    

    The variable p can change, but the data p points to is unmodifable.

    However, moving the const keyword to the left of the asterisk does not alter the meaning of the declaration:

    char const* p;
    

    I prefer the later since it becomes much easier to remember where to place the const keywords when declaring const pointers to const pointers:

    char const* const* p;
    

    Again, the variable p can change and the data pointed to is unmodifiable. Furthermore, the data is declared as const pointers meaning that it points to data that cannot be modified.

    The more common notation for this type is

    const char* const* p;
    

    Placing the const keyword immediately to the left of the asterisk it modifies (or ampersand for reference) makes it easy to create complex types involving the const keyword. For example, a pointer to const pointers:

    char const** p;
    

    and a const pointer to pointers:

    char* const* p;
    

    Remember to "read" pointer declarations from the right to the left, and don't declare more than one pointer in each statement to avoid a lot of confusion.

提交回复
热议问题