auto 关键字在 C++ 中,auto 关键字是 C++11 引入的一项强大特性,用于声明数据类型由推断得出的变量。
编译器会根据变量的初始值推断出它的类型,这能让代码更易读、更易维护。
看下面这个例子,其中用 auto 声明了几个变量:
auto dragon_population{3}; // dragon_population is deduced as an integer
auto westeros{7.7777}; // westeros is deduced as a double
auto wedding_location{"The Twins"}; // wedding_location is deduced as a const char*, not std::string
每种情况下,变量的类型都由初始化它时所用的值推断出来。
auto 关键字减少了显式类型的冗长写法,帮你写出更简洁、更易读的代码。
const std::vector<std::string> pigeon_pie{"flour", "butter", "pigeon", "salt"};
auto purple_wedding_pie{pigeon_pie};
purple_wedding_pie.emplace_back("the strangler");
在这段循环中,auto 把 purple_wedding_pie 的类型推断为 std::vector<std::string>,无需再次显式写出这个类型。
auto 关键字能与多种 C++ 结构配合使用,这使它成为现代 C++ 编程中用途广泛的工具。
auto& element{array[0]}; // reference to an element
const auto object{otherObject}; // const type version of otherObject's type
auto* ptr{&x}; // pointer to x with the same type as x, but as a pointer.
在后面的概念里,我们会经常看到 auto 关键字与 lambda 表达式、基于范围的 for 循环以及迭代器一起使用。
auto 尤其有用。auto 能减少杂乱、提升代码的可维护性。