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

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

    I agree with most of the answers given so far, on the other hand, some aspects are still missing.

    When defining interfaces, the const keyword is your friend. But you should know that it's also somewhat limited and sometimes even egoistic - this is what I'd call its downsides.

    Let's have another close look on the question:

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

    If you observe that you don't modify something, you may say that it's effectively a constant. Also code analysis tools can detect this, even your compiler will already know it. But this observation should not trigger an add-const reflex in you.

    Instead think about the variable itself, ask

    • Is it useful at all?
    • Is it also intended to be constant?

    Sometimes an intermediate variable can simply be removed, sometimes a small rework (adding or removing a function) can be done to improve the code.

    Adding the const keyword may harden your code against errors elsewhere, but also against changes at the declaration point.

    Let me also add a word about member variables that don't change. If you decide to declare a member variable const, you have to initialize it in the initializer list of the constructor of the containing class, this extends the preconditions for constructing objects of this class.

    So don't add const wherever your compiler allows for it. Do not be seduced to "petrify your code" ;-)

提交回复
热议问题