// case 1
const int i = 42;
const auto &k = i;
// case 2
const int i = 42;
auto &k = i;
在这种情况下,我们是否需要在 const
之前使用 auto
关键字? After all, a reference ( k
) to an auto-deduced type will include the top level const
of the object ( const
int i
)。所以我相信 k
在这两种情况下都是对一个常量( const int &k
)的整数的引用。
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
)?而在情况 2 中, auto
被替换为 const int
?
原文由 Steve Cho 发布,翻译遵循 CC BY-SA 4.0 许可协议
auto
关键字在编译时自动决定变量的类型。在第一种情况下,
auto
减少为int
const int
在第二种情况下减少为—。因此,您的两种情况都简化为与以下相同的代码:但是,最好明确使用 const 以获得更好的可读性并确保您的变量 TRULY 是
const
。