CppCoreGuidelines P.11 通过封装整理混乱代码
04 January 2022
代码散乱既难维护又容易隐藏 bug。尽量通过接口封装代码。
#include <iostream> #include <algorithm> using namespace std; int main() { int sz = 10; int* p = (int*) malloc(sizeof(int) * sz); int count = 0; int input_max = 20; int input_val = 0; for (;;) { int x = input_val++; if (input_val > input_max) break; if (count == sz) p = (int*) realloc(p, sizeof(int) * sz * 2); p[count++] = x; } for (int i=0; i<count; i++) cout << p[i] << " "; return 0; }
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
上面的代码进行底层内存操作、繁琐又容易出错。此处可以使用 vector
:
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> v; v.reserve(10); int input_max = 20; int input_val = 0; for (;;) { int x = input_val++; if (input_val > input_max) break; v.push_back(x); } ranges::for_each(v, [](const auto &x){cout << x << " ";}); return 0; }
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
用抽象层次更高的 vector
, span
, lock_guard
以及 future
。避免处理数组、联合体、类型转换和 gsl::owner
。尽量使用标准库和 GSL。