本文介绍了为什么 auto i = same_const_variable 不能推导出“const"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想知道为什么 auto 是为这种行为而设计的?

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

为什么类型 i 是int"而不是const int"?

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

这里有什么问题?

我认为理解为什么会帮助我们记住它

I think understand why will help us to remember it

推荐答案

auto 大多遵循与模板参数推导相同的类型推导规则.唯一的区别是在某些情况下,auto 会从 braced-init-list 推导出 std::initializer_list,而模板参数推导不会不要这样做.

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.

来自 N3337,§7.1.6.4 [dcl.spec.auto]

6   ... 为变量 d 推导出的类型是推导出的 A 使用模板参数推导规则从函数调用 (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   如果 P 不是引用类型:
    —— ...
    — 如果 A 是 cv 限定类型,A 类型的顶级 cv 限定符将被忽略扣除.

因此,在

auto i = ci;

顶级const 限定符被忽略,i 被推导出为int.

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

写作时

auto& i = ci;

then i 不再是引用类型并且上述规则不适用,因此保留了 const 限定符.

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

这篇关于为什么 auto i = same_const_variable 不能推导出“const"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 08:12