前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​​SL.str.1:使用std::string管理字符序列

C++核心准则​​SL.str.1:使用std::string管理字符序列

作者头像
面向对象思考
发布2020-10-30 11:31:12
4550
发布2020-10-30 11:31:12
举报

SL.str.1: Use std::string to own character sequences

SL.str.1:使用std::string管理字符序列

Reason(原因)

string correctly handles allocation, ownership, copying, gradual expansion, and offers a variety of useful operations.

string可以正确处理分配,所有权,复制,渐进增长并提供各种有用的操作。

Example(示例)

代码语言:javascript
复制
vector<string> read_until(const string& terminator)
{
    vector<string> res;
    for (string s; cin >> s && s != terminator; ) // read a word
        res.push_back(s);
    return res;
}

Note how >> and != are provided for string (as examples of useful operations) and there are no explicit allocations, deallocations, or range checks (string takes care of those).

(作为有用的操作的示例)注意>>和!=是如何提供给string的,代码中也没有显性的内存分配和释放或者内存检查(string会处理好这些)。

In C++17, we might use string_view as the argument, rather than const string& to allow more flexibility to callers:

在C++17中,我们可以使用string_view类型参数,而不是const string&以便为用户提供更多的灵活性。

代码语言:javascript
复制
vector<string> read_until(string_view terminator)   // C++17
{
    vector<string> res;
    for (string s; cin >> s && s != terminator; ) // read a word
        res.push_back(s);
    return res;
}
Example, bad(反面示例)

Don't use C-style strings for operations that require non-trivial memory management

不要将C风格字符串用于需要一定复杂度的内存管理的操作中。

代码语言:javascript
复制
char* cat(const char* s1, const char* s2)   // beware!
    // return s1 + '.' + s2
{
    int l1 = strlen(s1);
    int l2 = strlen(s2);
    char* p = (char*) malloc(l1 + l2 + 2);
    strcpy(p, s1, l1);
    p[l1] = '.';
    strcpy(p + l1 + 1, s2, l2);
    p[l1 + l2 + 1] = 0;
    return p;
}

Did we get that right? Will the caller remember to free() the returned pointer? Will this code pass a security review?

我们做对了么?调用者会记住释放返回的指针么?这段代码可以通过安全评审么?

Note(注意)

Do not assume that string is slower than lower-level techniques without measurement and remember that not all code is performance critical. Don't optimize prematurely

不要不经测算就假定string就会比低水平技术慢,并且需要明白不是所有的代码都对性能敏感。不要过早优化。

Enforcement(实施建议)

???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slstr1-use-stdstring-to-own-character-sequences

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SL.str.1: Use std::string to own character sequences
  • Reason(原因)
    • Example, bad(反面示例)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档