Search code examples
c++c++11autotype-deduction

why auto i = same_const_variable could not deduce "const"?


const int ci = 10;
auto i = ci;  // i will be "int" instead of "const int"
i = 20;

I am wondering why auto is designed for this kind of behaviour?

why the type i is "int" instead of "const int" ?

what is the concern here?

I think understand why will help us to remember it


Solution

  • auto mostly follows the same type deduction rules as template argument deduction. The only difference is that auto will deduce std::initializer_list from a braced-init-list in some cases, while template argument deduction doesn't do this.

    From N3337, §7.1.6.4 [dcl.spec.auto]

    6   ... The type deduced for the variable d is then the deduced A determined using the rules of template argument deduction from a function call (14.8.2.1), ...

    The behavior you're observing is the same as what template argument deduction would do when deducing types from a function call

    §14.8.2.1 [temp.deduct.call]

    2   If P is not a reference type:
        — ...
        — If A is a cv-qualified type, the top level cv-qualifiers of A’s type are ignored for type deduction.

    Thus, in

    auto i = ci;
    

    the top level const qualifier is ignored and i is deduced as int.

    When you write

    auto& i = ci;
    

    then i is no longer not a reference type and the above rule doesn't apply, so the const qualifier is retained.