C++核心准则ES.1: 标准库好于其他库和手写代码

C++核心准则ES.1: 标准库好于其他库和手写代码

ES.1: Prefer the standard library to other libraries and to "handcrafted code"

ES.1: 标准库好于其他库和手写代码

Reason(原因)

Code using a library can be much easier to write than code working directly with language features, much shorter, tend to be of a higher level of abstraction, and the library code is presumably already tested. The ISO C++ Standard Library is among the most widely known and best tested libraries. It is available as part of all C++ implementations.

使用库的代码比直接使用语言功能的代码更容易写,更简短,更趋向于高层次抽象,而且库代码更有可能被测试过。ISO C++标准库是最有名,经过最好测试的库之一。它作为C++实现的一部分,可以直接使用。

Example(示例)

<code>auto sum = accumulate(begin(a), end(a), 0.0);   // good/<code>

a range version of accumulate would be even better:

使用range的accumulate版本会更好:

<code>auto sum = accumulate(v, 0.0); // better/<code>

but don't hand-code a well-known algorithm:

但是不要试图硬编码实现常见算法:

<code>int max = v.size();   // bad: verbose, purpose unstated
double sum = 0.0;
for (int i = 0; i < max; ++i)

sum = sum + v[i];/<code>

Exception(例外)

Large parts of the standard library rely on dynamic allocation (free store). These parts, notably the containers but not the algorithms, are unsuitable for some hard-real-time and embedded applications. In such cases, consider providing/using similar facilities, e.g., a standard-library-style container implemented using a pool allocator.

很大一部分标准库依靠动态内存分配(自由存储)。这些部分,主要是容器而非算法,不大适合某些硬实时和嵌入式应用。在这样的情况下,考虑提供/使用相似的功能。例如从存储池中分配对象的标准库风格的容器。

Enforcement(实施建议)

Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?

不容易。寻找混乱的循环、嵌套循环、长函数、函数调用缺失、很少被使用的内置类型?还是确认圈复杂度?

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es1-prefer-the-standard-library-to-other-libraries-and-to-handcrafted-code


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

C++核心准则ES.1: 标准库好于其他库和手写代码


分享到:


相關文章: