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: 標準庫好於其他庫和手寫代碼


分享到:


相關文章: