why auto i = same_const_variable could not deduce “const”?

前端 未结 2 1909
北荒
北荒 2021-01-06 10:52
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 behavio

2条回答
  •  梦毁少年i
    2021-01-06 11:29

    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.

提交回复
热议问题