# C++核心准则边译边学-P.11 封装混乱的代码，而不是传播它们​

C++ 专栏收录该内容
561 篇文章 19 订阅

### P.11: Encapsulate messy constructs, rather than spreading through the code 封装混乱的代码，而不是传播它们

Reason（原因）

Messy code is more likely to hide bugs and harder to write. A good interface is easier and safer to use. Messy, low-level code breeds more such code.

Example（示例）

int sz = 100;int* p = (int*) malloc(sizeof(int) * sz);int count = 0;// ...for (;;) {    // ... read an int into x, exit loop if end of file is reached ...    // ... check that x is valid ...    if (count == sz)        p = (int*) realloc(p, sizeof(int) * sz * 2);    p[count++] = x;    // ...}

This is low-level, verbose, and error-prone. For example, we "forgot" to test for memory exhaustion. Instead, we could use vector:

vector<int> v;v.reserve(100);// ...for (int x; cin >> x; ) {    // ... check that x is valid ...    v.push_back(x);}

Note（注意）

The standards library and the GSL are examples of this philosophy. For example, instead of messing with the arrays, unions, cast, tricky lifetime issues, gsl::owner, etc., that are needed to implement key abstractions, such as vector, span, lock_guard, and future, we use the libraries designed and implemented by people with more time and expertise than we usually have. Similarly, we can and should design and implement more specialized libraries, rather than leaving the users (often ourselves) with the challenge of repeatedly getting low-level code well. This is a variant of the subset of superset principle that underlies these guidelines.

Enforcement（实施建议）

• Look for "messy code" such as complex pointer manipulation and casting outside the implementation of abstractions.

找到“混乱代码”，例如复杂指针操作或者除了实现抽象之外的类型转换。

• 2
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报