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
    评论
以下是使用7-Zip源代码解压1.tar.gz压缩包的C++代码示例: ```c++ #include <stdio.h> #include <string.h> #include "7z.h" #include "7zAlloc.h" #include "7zFile.h" #include "Archive/7z/7zExtract.h" int main(int argc, char *argv[]) { // 要解压缩的压缩包文件名 const char* archive_file = "1.tar.gz"; // 初始化7-Zip库 CrcGenerateTable(); SzArEx_Init(); // 打开压缩包文件 CSzFile archive; if (InFile_Open(&archive.file, archive_file)) { printf("Failed to open archive file: %s\n", archive_file); return 1; } // 解析压缩包文件头 CArchiveDatabaseEx db; SzArEx_Init(&db); ISzAlloc alloc = { SzAlloc, SzFree }; if (SzArEx_Open(&db, &archive.file, &alloc, &alloc)) { printf("Failed to open archive: %s\n", archive_file); InFile_Close(&archive.file); return 1; } // 遍历压缩包中的文件,解压缩指定的文件 UInt32 i; UInt32 blockIndex = 0xFFFFFFFF; /* it can have any value before first call (if outBuffer = 0) */ Byte *outBuffer = 0; /* it must be 0 before first call for each new archive. */ size_t outBufferSize = 0; /* it can have any value before first call (if outBuffer = 0) */ int extract_status = -1; for (i = 0; i < db.Database.NumFiles; i++) { size_t offset = 0; size_t outSizeProcessed = 0; const CSzFileItem *fileItem = db.Database.Files + i; size_t len = SzArEx_GetFileNameUtf16(&db, i, 0); if (SzArEx_IsDir(&db, i)) { continue; } // 判断是否为要解压的文件 const char *file_name = (const char*)malloc(len + 1); SzArEx_GetFileNameUtf8(&db, i, file_name); if (strcmp(file_name, "1.tar") != 0) { free(file_name); continue; } free(file_name); // 解压指定的文件 extract_status = SzArEx_Extract(&db, &archive.file, i, &blockIndex, &outBuffer, &outBufferSize, &offset, &outSizeProcessed, &alloc, &alloc); if (extract_status != SZ_OK) { printf("Failed to extract file: %s\n", "1.tar"); InFile_Close(&archive.file); return 1; } break; } // 关闭7-Zip库 SzArEx_Free(&db, &alloc); InFile_Close(&archive.file); SzFree(NULL, outBuffer); if (extract_status == SZ_OK) { printf("Extract file successful: %s\n", "1.tar"); } return 0; } ``` 该示例代码使用了7-Zip源代码中的7z.h、7zAlloc.h、7zFile.h和7zExtract.h等头文件,通过调用相应的函数实现了解压缩1.tar.gz压缩包中的1.tar文件的功能。在实际使用过程中,您需要根据具体情况进行相应的修改和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值