// 1 auto必须初始化
int x; // right
auto x; // wrong
auto x = 1; // right
// 2 auto 减少代码移植的工作量
int func();
auto x = func();
long func();
auto x = func();
// 3 避免类型不匹配
std::unordered_map<std::string, int> m;
for(const std::pair<std::string, int>& p : m) {
}
// std::unordered_map 的key是const的,所以std::pair 的类型不是std::pair<std::string, int>,
// 而是std::pair<const std::string, int>, 编译器会努力找一种方法把 std::pair<const std::string, int> 转化为 std::pair<std::string, int>.
// 主要通过拷贝m 创建一个临时对象,临时对象类型是p想绑定到对象的类型,,然后把p的引用绑定到这个临时对象上,循环结束销毁临时对象
// 使用auto可以避免类型不匹配的错误
for(const auto & p: m) {
} // 此时获取p地址,可以得到一个指向m中元素的指针,在没有auto的版本中p会指向一个临时对象,这个临时对象每次迭代完都会被销毁
// 使用auto也要避免踩到 item2 和item6中所述的陷阱
item5:优先考虑auto而非显示类型声明
于 2024-10-25 14:26:31 首次发布