🐭 尽量使用 auto
一般来说在保证代码可读性的前提下,应该尽量使用 auto 来局部的声明一切东西。相对于显式类型声明,auto 会给我们带来以下一些好处:
- auto 可以强制变量初始化
- auto 可以方便的定义复杂类型变量
- auto 可以方便的定义 Lambda 函数
- auto 可以正确的配合结构化绑定
- auto 可以正确的配合 range-based for 循环
- auto 可以某种程度上方便代码变更
当然不要滥用 auto,auto 会牺牲一点代码的可读性,但是代码的可读性是个多方面的问题,可以通过其他途径来改善,不妨想想动态编程语言的代码可读性问题。
🐂 auto 带来的好处上
既然 auto 有那么多好处,那我们应该在哪些地方合理的使用 auto 呢?这一小节主要覆盖上面提到的 1,2,3 部分。
代码示例 :
#include <forward_list>#include <iostream>#include <list>#include <string>#include <vector>int main(void) {using std::cout, std::vector, std::string, std::list, std::forward_list;cout.setf(std::ios_base::boolalpha);// case 1: force variable initializationint x0; // x0 is potentially uninitializedauto x1{0}; // auto force x1 initialization, otherwise code not compiles// case 2: define complex type variablevector<list<string>> vls{{"a", "b", "c"}, {"d", "e", "f"}};auto vls_size1 = vls.size();vector<list<string>>::size_type vls_size2 = vls.size();cout << std::is_same_v<decltype(vls_size1), decltype(vls_size2)> << '\n'; // trueunsigned vls_size3 = vls.size(); // here potentially overflow// change to use the forward_list instead of listvector<forward_list<string>> vfls{{"a", "b", "c"}, {"d", "e", "f"}};auto vls_size4 = vfls.size(); // use auto, does not need to change the type details// case 3: define lambda// directly use the lambda comp1 is more easy and effective than comp2auto comp1 = [](const int a, const int b) { return a < b; };std::function<bool(const int a, const int b)> comp2 = [](const int a, const int b) {return a < b;};// define complex lambda that hard to write std::function typeusing std::placeholders::_1;int L = 4, U = 9;auto isLessThanU = std::bind(std::less<int>(), _1, std::cref(U));auto isGreaterThanL = std::bind(std::greater<int>(), _1, std::cref(L));auto pred = std::bind(std::logical_and<bool>(), isLessThanU, isGreaterThanL);return 0;}
:::tips 对于复杂类型的定义,使用 auto 简直太方便了,应该总是使用 auto 来定义 Lambda 函数 :::
🐯 auto 带来的好处下
这一小节主要覆盖上面提到的 4,5,6 部分,尤其是要注意正确使用 auto 来「无脑」的避免不必要的由于类型不匹配而导致的运行时拷贝开销。
#include <iostream>#include <string>#include <unordered_map>int main(void) {using std::cout, std::is_same_v, std::string;cout.setf(std::ios_base::boolalpha);using map_t = std::unordered_map<string, int>;map_t m{{"one", 1}, {"two", 2}, {"three", 3}, {"four", 4}};// case 4: structured bindingauto [iter1, inst1] = m.emplace(std::pair{"four", 4});auto iter2 = m.emplace(std::pair{"four", 4});assert(iter1 == iter2.first);assert(inst1 == iter2.second);cout << std::addressof(iter1->first) << '\n'; // 0x7f89fe405850// case 5: range-based for loopcout << is_same_v<map_t::value_type, std::pair<const string, int>> << '\n'; // true// type mismatch will call std::pair copy ctorfor (const std::pair<string, int> &p : m) {if (p.first == iter1->first) {cout << std::addressof(p.first) << '\n'; // 0x7ffee9c82a80}}// type match, just use the referencefor (const std::pair<const string, int> &p : m) {if (p.first == iter1->first) {cout << std::addressof(p.first) << '\n'; // 0x7f89fe405850}}// use auto, no need to take care the type any morefor (const auto &[k, v] : m) {if (k == iter1->first) {cout << std::addressof(k) << '\n'; // 0x7f89fe405850}}return 0;}
:::tips
auto,结构化绑定与 range-based-for 循环简直是绝配,非常实用
关于方便代码变更,主要是指 auto 没有写死类型,因而具有类型的普适性,能主动适应代码变更
:::
🐰 总结
- 合理的使用 auto 能协助我们写出更正确的代码
- 在局部范围内尽量使用 auto,不至于影响代码的可读性
