C++ auto类型说明符

2020-01-06 14:50:14刘景俊

如果希望推断出的auto类型是一个顶层const,需要明确指出:


const auto f = ci; // ci 的推演类型是int,f是const int类型

还可以将引用的类型设置为auto,此时原来的初始化规则仍然适用:


auto &g = ci; // g是一个整型常量引用,绑定到ci
auto &h = 42; // Error: 不能为非常量引用绑定字面值
const auto &j = 42; // OK: 可以为常量引用绑定字面值

切记,符号*和&只从属于某个声明,而非基本数据类型的一部分,因此初始值必须是同一类型:


auto k = ci, &l = i; // k是整数,l是整型引用
auto &m = ci, *p = &ci; // m是对整型常量的引用,p是指向整型常量的指针
auto &n = i, *p2 = &ci; // Error: i的类型是int,而&ci的类型是const int

附上更多示例代码:

下面的声明等效。在第一个语句中,将变量j 声明为类型 int。在第二个语句中,将变量 k 推导为类型 int,因为初始化表达式 (0) 是整数


int j = 0; // Variable j is explicitly type int.
auto k = 0; // Variable k is implicitly type int because 0 is an integer.

以下声明等效,但第二个声明比第一个更简单。使用 auto 关键字的最令人信服的一个原因是简单


map<int,list<string>>::iterator i = m.begin(); 
auto i = m.begin(); 

使用 iter 和 elem 启动循环时


#include <deque>
using namespace std;

int main()
{
  deque<double> dqDoubleData(10, 0.1);

  for (auto iter = dqDoubleData.begin(); iter != dqDoubleData.end(); ++iter)
  { /* ... */ }

  // prefer range-for loops with the following information in mind
  // (this applies to any range-for with auto, not just deque)

  for (auto elem : dqDoubleData) // COPIES elements, not much better than the previous examples
  { /* ... */ }

  for (auto& elem : dqDoubleData) // observes and/or modifies elements IN-PLACE
  { /* ... */ }

  for (const auto& elem : dqDoubleData) // observes elements IN-PLACE
  { /* ... */ }
}

下面的代码片段使用 new 运算符和指针声明来声明指针


double x = 12.34;
auto *y = new auto(x), **z = new auto(&x);

下一个代码片段在每个声明语句中声明多个符号。请注意,每个语句中的所有符号将解析为同一类型。