C++核心準(zhǔn)則?討論:持有沒(méi)有被句柄管理的資源時(shí)切勿拋出異常

Discussion: Never throw while holding a resource not owned by a handle
討論:持有沒(méi)有被句柄管理的資源時(shí)切勿拋出異常
Reason(原因)
That would be a leak.
這回引發(fā)資源泄露。
Example(注意)
void f(int i)
{
FILE* f = fopen("a file", "r");
ifstream is { "another file" };
// ...
if (i == 0) return;
// ...
fclose(f);
}
If?i == 0?the file handle for?a file?is leaked. On the other hand, the?ifstream?for?another file?will correctly close its file (upon destruction). If you must use an explicit pointer, rather than a resource handle with specific semantics, use a?unique_ptr?or a?shared_ptr?with a custom deleter:
如果i == 0,則文件的句柄發(fā)生泄漏。另一方面,另一個(gè)文件的ifstream將正確關(guān)閉其文件(銷毀時(shí))。如果必須使用顯式指針,而不是具有特定語(yǔ)義的資源句柄,請(qǐng)使用帶有自定義刪除器的unique_ptr或shared_ptr:
void f(int i)
{
unique_ptr f(fopen("a file", "r"), fclose);
// ...
if (i == 0) return;
// ...
}
Better:
更好的做法:
void f(int i)
{
ifstream input {"a file"};
// ...
if (i == 0) return;
// ...
}Enforcement(實(shí)施建議)
A checker must consider all "naked pointers" suspicious. A checker probably must rely on a human-provided list of resources. For starters, we know about the standard-library containers,?string, and smart pointers. The use of?span?and?string_view?should help a lot (they are not resource handles).
檢查器必須將所有“暴露的指針”視為可疑。檢查器可能必須依靠人工提供的資源列表。首先,我們了解標(biāo)準(zhǔn)庫(kù)容器,字符串和智能指針。使用span和string_view應(yīng)該會(huì)很有幫助(它們不是資源句柄)。
原文鏈接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#discussion-never-throw-while-holding-a-resource-not-owned-by-a-handle
新書介紹
《實(shí)戰(zhàn)Python設(shè)計(jì)模式》是作者最近出版的新書,拜托多多關(guān)注!

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