does `const auto` have any meaning?

前端 未结 4 551
无人及你
无人及你 2020-12-23 16:06

I think the question is clear enough. Will the auto keyword auto-detect const-ness, or always return a non-const type, even if there are eg. two versions of a f

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-23 16:15

    Compiler deduces the type for the auto qualifier. If a deduced type is some_type, const auto will be converted to const some_type. However, a good compiler will examine the whole scope of auto variable and find if the value of it changes anywhere. If not, compiler itself will deduce type like this: auto -> const some_type. I've tried this in Visual studio express 2012 and machine code produced is the same in both cases, I'm not sure that each and every compiler will do that. But, it is a good practice to use const auto for three reasons:

    • Preventing coding errors. You intended for this variable not to change but somehow somewhere in its scope, it is changed.
    • Code readability is improved.
    • You help the compiler if for some reason it doesn't deduce const for auto.

提交回复
热议问题