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(示例)

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

a range version of accumulate would be even better:

使用range的accumulate版本會更好:

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

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

但是不要試圖硬編碼實現常見算法:

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

 

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

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章