What's the point of const pointers?

后端 未结 17 1872
粉色の甜心
粉色の甜心 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:52

    I make a point of using only const arguments because this enables more compiler checks: if I accidentally re-assign an argument value inside the function, the compiler bites me.

    I rarely reuse variables, it’s cleaner to create new variables to hold new values, so essentially all my variable declarations are const (except for some cases such as loop variables where const would prevent the code from working).

    Note that this makes only sense in the definition of a function. It doesn’t belong in the declaration, which is what the user sees. And the user doesn’t care whether I use const for parameters inside the function.

    Example:

    // foo.h
    int frob(int x);
    
    // foo.cpp
    int frob(int const x) {
       MyConfigType const config = get_the_config();
       return x * config.scaling;
    }
    

    Notice how both the argument and the local variable are const. Neither is necessary but with functions that are even slightly larger, this has repeatedly saved me from making mistakes.

提交回复
热议问题