What's the point of const pointers?

后端 未结 17 1914
粉色の甜心
粉色の甜心 2020-11-30 17:28

I\'m not talking about pointers to const values, but const pointers themselves.

I\'m learning C and C++ beyond the very basic stuff and just until today I realized t

17条回答
  •  生来不讨喜
    2020-11-30 17:42

    ...today I realized that pointers are passed by value to functions, which makes sense.

    (imo) it really doesn't make sense as the default. the more sensible default is to pass as non-reassignable pointer (int* const arg). that is, i would have preferred that pointers passed as arguments were implicitly declared const.

    So what's the advantage of const?

    the advantage is that it's easy enough and sometimes unclear when you do modify the address the argument points to, such that you can introduce a bug when it is not const rather easily. altering the address is atypical. it's clearer to create a local variable if your intent is to modify the address. as well, raw pointer manipulation is an easy way to introduce bugs.

    so it's clearer to pass by immutable address and create a copy (in those atypical cases) when you want to alter the address the argument points to:

    void func(int* const arg) {
        int* a(arg);
        ...
        *a++ = value;
    }
    

    adding that local is virtually free, and it reduces the chance for errors, while improving readability.

    at a higher level: if you are manipulating the argument as an array, it's typically clearer and less error prone to the client to declare the argument as a container/collection.

    in general, adding const to values, arguments, and addresses is a good idea because you don't always realize the side effects, which the compiler happily enforces. therefore, it's as useful as const as used in other several other cases (e.g. the question is similar to 'Why should I declare values const?'). fortunately, we also have references, which cannot be reassigned.

提交回复
热议问题