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

前端 未结 6 1965
清歌不尽
清歌不尽 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:37

    There are no downsides to marking variables you don't modify const.

    There are some up-sides though: the compiler will help you diagnose when you unintentionally modify a variable you shouldn't/didn't mean to and the compiler may (although due to the language having const_cast and mutable this is rare) generate better code.

    So, I'd advise; use const where you can. There are no downsides and your compiler can potentially help you spot bugs. No reason not to (except for a bit of extra typing).

    Note that this extends to member functions as well. Make them const when you can - it lets them be used in more contexts and helps users reason about the code ("calling this function won't modify the object" is valuable information).

提交回复
热议问题