C++ const keyword - use liberally?

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

提交回复
热议问题