const auto & 之间的区别和汽车 &如果引用对象是 const [英] Difference between const auto & and auto & if object of reference is const

查看:25
本文介绍了const auto & 之间的区别和汽车 &如果引用对象是 const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// case 1
const int i = 42;
const auto &k = i;

// case 2
const int i = 42;
auto &k = i;

在这种情况下,我们需要在 auto 之前使用 const 关键字吗?毕竟,对自动推导类型的引用 (k) 将包括对象的顶级 const (constcode> int i).所以我相信 k 在这两种情况下都会引用一个常量(const int &k).

Do we need the const keyword before auto in this scenario? After all, a reference (k) to an auto-deduced type will include the top level const of the object (const int i). So I believe k will be a reference to an integer that is constant (const int &k) in both cases.

如果这是真的,那是否意味着 const auto &k = i; 在 case 1 被编译器替换为 const int &k = i;代码>(auto 被替换为 int)?而在情况 2 中,auto 被替换为 const int?

If that is true, does that mean that const auto &k = i; in case 1 is replaced by the compiler as just const int &k = i; (auto being replaced with int)? Whereas in case 2, auto is replaced with const int?

推荐答案

auto 关键字在编译时自动决定变量的类型.

auto keyword automatically decides the type of the variable at compile time.

在第一种情况下,auto 被简化为 int,而在第二种情况下它被简化为 const int.因此,您的两个案例都简化为与以下相同的代码:

In your first case, auto is reduced to int where it's reduced to const int in the second case. So, both of your cases are reduced to the same code as:

const int &k = i;

但是,为了更好的可读性并确保您的变量真正const,最好显式地使用const.

However, it's better to have the const explicitly for better readability and to make sure your variable TRULY is const.

这篇关于const auto & 之间的区别和汽车 &如果引用对象是 const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆