Are there any downsides to marking all variables you don't modify const?

前端 未结 6 1975
清歌不尽
清歌不尽 2021-01-07 16:24

After much googling I\'ve found a lot about marking functions and their parameters as const, but no guide on marking variables as const.

He

6条回答
  •  情话喂你
    2021-01-07 16:50

    For the local variable size_t length in a short method like this it doesn't really matter. The downside of extra verbosity basically balances with the relative safety of avoiding typos accidentally modifying the length. Do whatever your local style guide, or your own gut feeling tells you.

    For a longer or more complex method, it might be different. But then again, if you have so complex a method that it matters, maybe you should at least consider refactoring your code to simpler pieces... Anyway, if you read and understand the code, extra hint provided by explicit const is kinda irrelevant - nice but irrelevant.


    Slightly related, though you didn't ask about it: For the reference parameter of your example method, you definitely do want const, because you might need to pass it a const string. Only if you want to disable passing const string (because you think you'll add code to modify it), you should omit const there.

提交回复
热议问题