C++ const keyword - use liberally?

前端 未结 12 2438
甜味超标
甜味超标 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 18:59

    I recommend reading Herb Sutter. Exceptional C++. There is a chapter "Const-Correctness".

    "In fact, to the compiler, the function signature is the same whether you include this const in front of a value parameter or not."

    It means that this signature

    void print(int number);
    

    is effectively the same as this:

    void print(int const number);
    

    So, to the compiler there is no difference how you declare a function. And you can't overload it by putting the const keyword in front of a pass by value parameter.

    Read further, what Herb Sutter recommends:

    "Avoid const pass-by-value parameters in function declarations. Still make the parameter const in the same function's definition if it won't be modified."

    He recommends to avoid this:

    void print(int const number);
    

    Because that const is confusing, verbose and redundant.

    But in the definition, you should do that (if you won't change the parameter):

    void print(int const number)
    {
       // I don't want to change the number accidentally here
       ...
    }
    

    So, you'll be sure that even after 1000 lines of function's body you always have the number untouched. The compiler will prohibit you from passing the number as a non-const reference to another function.

提交回复
热议问题