C++核心準(zhǔn)則??SL.str.1:使用std::string管理字符序列

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可以正確處理分配,所有權(quán),復(fù)制,漸進增長并提供各種有用的操作。
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的,代碼中也沒有顯性的內(nèi)存分配和釋放或者內(nèi)存檢查(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類型參數(shù),而不是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風(fēng)格字符串用于需要一定復(fù)雜度的內(nèi)存管理的操作中。
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?
我們做對了么?調(diào)用者會記住釋放返回的指針么?這段代碼可以通過安全評審么?
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
不要不經(jīng)測算就假定string就會比低水平技術(shù)慢,并且需要明白不是所有的代碼都對性能敏感。不要過早優(yōu)化。
Enforcement(實施建議)
???
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slstr1-use-stdstring-to-own-character-sequences
新書介紹
《實戰(zhàn)Python設(shè)計模式》是作者最近出版的新書,拜托多多關(guān)注!

本書利用Python 的標(biāo)準(zhǔn)GUI 工具包tkinter,通過可執(zhí)行的示例對23 個設(shè)計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟件開發(fā)工作中每個設(shè)計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設(shè)計模式的利弊,并合理運用設(shè)計模式。
對設(shè)計模式感興趣而且希望隨學(xué)隨用的讀者通過本書可以快速跨越從理解到運用的門檻;希望學(xué)習(xí)Python GUI 編程的讀者可以將本書中的示例作為設(shè)計和開發(fā)的參考;使用Python 語言進行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書中的示例為基礎(chǔ),迅速構(gòu)建自己的系統(tǒng)架構(gòu)。
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
