C++ : Different deduction of type auto between const int * and cont int &

标签 c++ c++11

这里是代码示例。

a. int ii = 0;
b. const int ci = ii;
c. auto e = &ci; --> e is const int *
d. auto &f = 42; --> invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
e. const auto &g = 42 --> ok

观察:
1. 对于 c) 子句,自动推导类型 const
2. 对于子句d),不会自动推导出类型const
3. 对于条款 e),必须手动添加类型 const 才能使其工作。

为什么子句 c 而不是 d 会自动推导类型 const?

最佳答案

原因不是 const-ness,而是 r-value-ness。

您不能对右值进行非常量引用。

如果您想知道什么是 r 值,最初的想法是只能位于赋值右侧的东西。

为了获取编译时常量的地址,编译器首先复制它,并为您提供该地址。要启用该行为,引用必须明确为 const

要完成答案: 案例

  • c) ci的类型是const int,因此&ci的类型是const int的地址>.
  • d) 42 的类型是intauto 推导为 intf 被声明为对 int 的引用,但未能绑定(bind)到 r-value
  • e) g的类型是const int &,可以绑定(bind)编译时间常量。

关于C++ : Different deduction of type auto between const int * and cont int &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32873834/

相关文章:

c++ - 在 std::move() 之后使字符串为空的机制

c++ - 使用 std::vector::erase 和 const_iterators

c++ - Range-for-loops 和 std::vector<bool>

c++ - 多态对象销毁和并发

c++ - 无法使用regex c++ 11 std在Windows中运行使用minGW编译的程序

C++ 复制构造函数和默认构造函数

c++ - 是否可以使用 Visual Studio 2013 Community Edition 创建静态库 C++?

c++ - Qt 模型/ View 委托(delegate) : How to simply translate text data?

c++ - 为什么 std::move( arg ) 改变 arg 参数?

c++ - 在 C++11 的 lambda 中使用封闭函数中的模板类型可以吗?