C++ const keyword - use liberally?

前端 未结 12 2430
甜味超标
甜味超标 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.

提交回复
热议问题