C++ const keyword - use liberally?

前端 未结 12 2407
甜味超标
甜味超标 2020-12-04 18:12

In the following C++ functions:

void MyFunction(int age, House &purchased_house)
{
    ...
}


void MyFunction(const int age, House &purchased_house)         


        
相关标签:
12条回答
  • 2020-12-04 19:12

    First, it's just an implementation detail, and if you put const there, don't put it in the declaration set (header). Only put it in the implementation file:

    // header
    void MyFunction(int age, House &purchased_house);
    
    // .cpp file
    void MyFunction(const int age, House &purchased_house);
    {
        ...
    }
    

    Whether or not a parameter is const in a definition is purely an implementation detail, and should not be part of the interface.

    I've not seen this sort of thing often, and i also don't do this. Having the parameter const would confuse me more often than help, because i would immediately pattern-match-fail it to "const int &age" :) The matter of course is entirely different from having const at another level:

    // const is a *good* thing here, and should not be removed,
    // and it is part of the interface
    void MyFunction(const string &name, House &purchased_house);
    {
        ...
    }
    

    In this case, the const will affect whether the function can change the caller's argument. Const in this meaning should be used as often as possible, because it can help ensuring program correctness and improve self-documenting the code.

    0 讨论(0)
  • 2020-12-04 19:12

    You're correct, the only purpose of "const int age" is that age can not be changed. This can be however very confusing for most of programmers. So if these approach is not used widely in your code, I'd advice to omit const.

    0 讨论(0)
  • 2020-12-04 19:13

    See Meyers and 'Effective C++' on this, and do use const liberally, especially with pass-by-reference semantics.

    In this case of atomic variables, efficiency does not matter but code clarity still benefits.

    0 讨论(0)
  • 2020-12-04 19:13

    Here are some great articles and a book I found explaining the advantages of using const:

    • C++ const Correctness

    • Advice From the C++ Experts: Be Const-Correct

    • Effective C++ from Scott Meyers


    Can I propose the following maxim to you?

    If an object/variable can be qualified has being constant, it should be. At worst, it will not cost anything. At best, you will be documenting the role of the object/variable in your code and it will allow the compiler the opportunity to optimize your code even more.

    Some compilers neglect to exploit the potential of optimization with the use of 'const' and that has lead many experts to neglect the use of constant parameters by value when it could be used. This practice takes more strictness, but it will not be harmful. At worst, you do not lose anything , but you do not gain anything too and at best, you win from using this approach.


    For those who do not seem to understand the utility of a const in a by value parameter of a function/method... here is a short example that explains why:

    .cpp

    void WriteSequence(int const *, const int);
    
    int main()
    {
        int Array[] = { 2, 3, 4, 10, 12 };
        WriteSequence(Array, 5);
    }
    
    
    #include <iostream>
    using std::cout;
    using std::endl;
    void WriteSequence(int const *Array, const int MAX)
    {
        for (int const * i = Array; i != Array + MAX; ++i)
          cout << *i << endl;
    }
    

    What would had happen if I would had removed the const in front of int MAX and I had written MAX + 1 inside like this?

    void WriteSequence(int Array[], int MAX)
    {
        MAX += MAX;
        for (int * i = Array; i != Array + MAX; ++i)
          cout << *i << endl;
    }
    

    Well your program would crash! Now, why would someone write "MAX += MAX;" ? Perhaps human error, maybe the programmer was not feeling well that day or perhaps the programmer simply did not know how to write C/C++ code. If you would have had const, the code would have not even compiled!

    Safe code is good code and it does not cost anything to add "const" when you have it!


    Here is an answer from a different post for a very similar question:

    "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).

    Here is the link: answer.

    0 讨论(0)
  • 2020-12-04 19:14

    Second variant is better. In the first one you can accidently change variable age.

    0 讨论(0)
  • 2020-12-04 19:14

    Having a primitive type that is passed by value const is pretty much worthless. Passing a const to a function is generally useful as a contract with the caller that the funciton will not change the value. In this case, because the int is passed by value, the function can't make any changes that will be visible outside the function.

    On the other hand, rreferences and non trivial object types should always use const if there is not going to be any changes made to the object. In theory this might allow for some optimization, but the big win is the contract I mentioned above. The downside is of course, that it can make your interface much larger, and const it a tough thing to retrofit into an existing system (or with a 3rd party API not using const everywhere).

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