Benefits of using “const” with scalar type? (e.g. “const double” or “const int”)

后端 未结 4 1631
[愿得一人]
[愿得一人] 2021-01-02 03:55
///////////////////////////////////////
class A {
    ...
    const double funA(void)
    {...}
};

A a;
double x = a.funA(); 
// although the intention is to
// enf         


        
相关标签:
4条回答
  • 2021-01-02 04:28

    From my point of view, it is NOT a good practice to change the pass-in parameter

    Then it makes sense to declare that by using the const on the argument in the definition of the function. Not everybody follows the practice, so having the const on the argument is better for future readers of your code than having to scan the whole function body for modifications to the argument.

    And even if you follow the practice it's easy to modify a variable by mistake (the classic typo of = instead of == or passing the arg via non-const ref or pointer). The const argument in the implementation prevents this.

    On the other hand const int argument in the declaration (if separate from definition) does not make sense.

    0 讨论(0)
  • 2021-01-02 04:29

    In practice, there is no real benefits for scalars.

    However, in theory it could help a compiler to perform additional optimizations, such as passing a reference to the constant instead of copying the double value.

    0 讨论(0)
  • 2021-01-02 04:30

    When returning by value the constant has no effect as it cannot be enforced anyway. Some compilers issue a warning. However it DOES make sense to return a pointer/reference to constant data.

    When passing an argument into a function it is preferable (safer, allows for compiler optimizations) to pass it as a constant unless you absolutely need to change the data.

    0 讨论(0)
  • 2021-01-02 04:34

    the const-keyword tells the Compiler "In my function setB i Wont change the Argument. If you want to Optimize for Multithreading you can use this Variable the same Time in another context, because my Work wont change it."

    So i would say, in Progamming-logic, the second variant is better, like you said it has "little meaning", but in wider logic if you see what really happens, you should declare const, what is const, and dont declare const what isnt const. It is kind of a documentation the compiler understands and maybe will use to optimize your code!

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