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

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

    I know such a small, simple example really doesn't show any huge benefit to this, but it seems like it'd be helpful in a larger codebase where you might accidentally mutate a variable you shouldn't have mutated.

    The problem is that this basically never actually happens.

    On the other hand, const is a disease that will spread through your codebase like a plague. As soon as you declare a const variable, all the things you need on it must be const, and so they must only call const functions, and it just never stops.

    const isn't remotely worth the price you pay for it in the infinite majority of situations. There's only a couple of cases where const actually protects you (e.g. set keys), but even then, it's debatable if you'd have to be a total moron to try that in the first place, and probably not worth all the language rules and incessant code duplication and redundant metalogic.

    const is a nice idea that might be nice in theory, but the practical realities are that const is a total waste of time and space. Burn it with fire.

提交回复
热议问题