前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.1: 标准库好于其他库和手写代码

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

作者头像
面向对象思考
发布2020-04-16 10:54:58
3760
发布2020-04-16 10:54:58
举报

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

代码语言:javascript
复制
auto sum = accumulate(begin(a), end(a), 0.0);   // good

a range version of accumulate would be even better:

使用range的accumulate版本会更好:

代码语言:javascript
复制
auto sum = accumulate(v, 0.0); // better

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

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

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Exception(例外)
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档