c++ malloc能给string_C++核心准则SL.str.1:使用std::string管理字符序列

c1500e86a8db2c9e5c09654eee8b513a.png

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

vector read_until(const string& terminator)
{
vector 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&以便为用户提供更多的灵活性。

vector read_until(string_view terminator)   // C++17
{
vector 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风格字符串用于需要一定复杂度的内存管理的操作中。

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

新书介绍

《实战Python设计模式》是作者最近出版的新书,拜托多多关注!

e604cd827c3f7e4184a063ead33a6a21.png

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。


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

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

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

0cd546a236d0e9406d68f85fe8bbd85f.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值