Use of 'const' for function parameters

前端 未结 30 2850
借酒劲吻你
借酒劲吻你 2020-11-22 03:06

How far do you go with const? Do you just make functions const when necessary or do you go the whole hog and use it everywhere? For example, imag

相关标签:
30条回答
  • 2020-11-22 03:37

    On compiler optimizations: http://www.gotw.ca/gotw/081.htm

    0 讨论(0)
  • 2020-11-22 03:38

    There's really no reason to make a value-parameter "const" as the function can only modify a copy of the variable anyway.

    The reason to use "const" is if you're passing something bigger (e.g. a struct with lots of members) by reference, in which case it ensures that the function can't modify it; or rather, the compiler will complain if you try to modify it in the conventional way. It prevents it from being accidentally modified.

    0 讨论(0)
  • 2020-11-22 03:39

    I say const your value parameters.

    Consider this buggy function:

    bool isZero(int number)
    {
      if (number = 0)  // whoops, should be number == 0
        return true;
      else
        return false;
    }
    

    If the number parameter was const, the compiler would stop and warn us of the bug.

    0 讨论(0)
  • 2020-11-22 03:39

    I use const on function parameters that are references (or pointers) which are only [in] data and will not be modified by the function. Meaning, when the purpose of using a reference is to avoid copying data and not to allow changing the passed parameter.

    Putting const on the boolean b parameter in your example only puts a constraint on the implementation and doesn't contribute for the class's interface (although not changing parameters is usually advised).

    The function signature for

    void foo(int a);
    

    and

    void foo(const int a);
    

    is the same, which explains your .c and .h

    Asaf

    0 讨论(0)
  • 2020-11-22 03:39

    Const parameter is useful only when the parameter is passed by reference i.e., either reference or pointer. When compiler sees a const parameter, it make sure that the variable used in the parameter is not modified within the body of the function. Why would anyone want to make a by-value parameter as constant? :-)

    0 讨论(0)
  • 2020-11-22 03:41

    "const is pointless when the argument is passed by value since you will not be modifying the caller's object."

    Wrong.

    It's about self-documenting your code and your assumptions.

    If your code has many people working on it and your functions are non-trivial then you should mark "const" any and everything that you can. When writing industrial-strength code, you should always assume that your coworkers are psychopaths trying to get you any way they can (especially since it's often yourself in the future).

    Besides, as somebody mentioned earlier, it might help the compiler optimize things a bit (though it's a long shot).

    0 讨论(0)
提交回复
热议问题