🐭 尽量使用 auto

一般来说在保证代码可读性的前提下,应该尽量使用 auto 来局部的声明一切东西。相对于显式类型声明,auto 会给我们带来以下一些好处:

  1. auto 可以强制变量初始化
  2. auto 可以方便的定义复杂类型变量
  3. auto 可以方便的定义 Lambda 函数
  4. auto 可以正确的配合结构化绑定
  5. auto 可以正确的配合 range-based for 循环
  6. auto 可以某种程度上方便代码变更

当然不要滥用 auto,auto 会牺牲一点代码的可读性,但是代码的可读性是个多方面的问题,可以通过其他途径来改善,不妨想想动态编程语言的代码可读性问题。

🐂 auto 带来的好处上

既然 auto 有那么多好处,那我们应该在哪些地方合理的使用 auto 呢?这一小节主要覆盖上面提到的 1,2,3 部分。
代码示例 :

  1. #include <forward_list>
  2. #include <iostream>
  3. #include <list>
  4. #include <string>
  5. #include <vector>
  6. int main(void) {
  7. using std::cout, std::vector, std::string, std::list, std::forward_list;
  8. cout.setf(std::ios_base::boolalpha);
  9. // case 1: force variable initialization
  10. int x0; // x0 is potentially uninitialized
  11. auto x1{0}; // auto force x1 initialization, otherwise code not compiles
  12. // case 2: define complex type variable
  13. vector<list<string>> vls{{"a", "b", "c"}, {"d", "e", "f"}};
  14. auto vls_size1 = vls.size();
  15. vector<list<string>>::size_type vls_size2 = vls.size();
  16. cout << std::is_same_v<decltype(vls_size1), decltype(vls_size2)> << '\n'; // true
  17. unsigned vls_size3 = vls.size(); // here potentially overflow
  18. // change to use the forward_list instead of list
  19. vector<forward_list<string>> vfls{{"a", "b", "c"}, {"d", "e", "f"}};
  20. auto vls_size4 = vfls.size(); // use auto, does not need to change the type details
  21. // case 3: define lambda
  22. // directly use the lambda comp1 is more easy and effective than comp2
  23. auto comp1 = [](const int a, const int b) { return a < b; };
  24. std::function<bool(const int a, const int b)> comp2 = [](const int a, const int b) {
  25. return a < b;
  26. };
  27. // define complex lambda that hard to write std::function type
  28. using std::placeholders::_1;
  29. int L = 4, U = 9;
  30. auto isLessThanU = std::bind(std::less<int>(), _1, std::cref(U));
  31. auto isGreaterThanL = std::bind(std::greater<int>(), _1, std::cref(L));
  32. auto pred = std::bind(std::logical_and<bool>(), isLessThanU, isGreaterThanL);
  33. return 0;
  34. }

:::tips 对于复杂类型的定义,使用 auto 简直太方便了,应该总是使用 auto 来定义 Lambda 函数 :::

🐯 auto 带来的好处下

这一小节主要覆盖上面提到的 4,5,6 部分,尤其是要注意正确使用 auto 来「无脑」的避免不必要的由于类型不匹配而导致的运行时拷贝开销。

  1. #include <iostream>
  2. #include <string>
  3. #include <unordered_map>
  4. int main(void) {
  5. using std::cout, std::is_same_v, std::string;
  6. cout.setf(std::ios_base::boolalpha);
  7. using map_t = std::unordered_map<string, int>;
  8. map_t m{{"one", 1}, {"two", 2}, {"three", 3}, {"four", 4}};
  9. // case 4: structured binding
  10. auto [iter1, inst1] = m.emplace(std::pair{"four", 4});
  11. auto iter2 = m.emplace(std::pair{"four", 4});
  12. assert(iter1 == iter2.first);
  13. assert(inst1 == iter2.second);
  14. cout << std::addressof(iter1->first) << '\n'; // 0x7f89fe405850
  15. // case 5: range-based for loop
  16. cout << is_same_v<map_t::value_type, std::pair<const string, int>> << '\n'; // true
  17. // type mismatch will call std::pair copy ctor
  18. for (const std::pair<string, int> &p : m) {
  19. if (p.first == iter1->first) {
  20. cout << std::addressof(p.first) << '\n'; // 0x7ffee9c82a80
  21. }
  22. }
  23. // type match, just use the reference
  24. for (const std::pair<const string, int> &p : m) {
  25. if (p.first == iter1->first) {
  26. cout << std::addressof(p.first) << '\n'; // 0x7f89fe405850
  27. }
  28. }
  29. // use auto, no need to take care the type any more
  30. for (const auto &[k, v] : m) {
  31. if (k == iter1->first) {
  32. cout << std::addressof(k) << '\n'; // 0x7f89fe405850
  33. }
  34. }
  35. return 0;
  36. }

:::tips auto,结构化绑定与 range-based-for 循环简直是绝配,非常实用
关于方便代码变更,主要是指 auto 没有写死类型,因而具有类型的普适性,能主动适应代码变更 :::

🐰 总结

  1. 合理的使用 auto 能协助我们写出更正确的代码
  2. 在局部范围内尽量使用 auto,不至于影响代码的可读性