c++ file* 句柄泄漏_C++核心准则?讨论:持有没有被句柄管理的资源时切勿抛出异常...
Discussion: Never throw while holding a resource not owned by a handle
討論:持有沒有被句柄管理的資源時切勿拋出異常
Reason(原因)
That would be a leak.
這會引發資源泄露。
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,則文件的句柄發生泄漏。另一方面,另一個文件的ifstream將正確關閉其文件(銷毀時)。如果必須使用顯式指針,而不是具有特定語義的資源句柄,請使用帶有自定義刪除器的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(實施建議)
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).
檢查器必須將所有“暴露的指針”視為可疑。檢查器可能必須依靠人工提供的資源列表。首先,我們了解標準庫容器,字符串和智能指針。使用span和string_view應該會很有幫助(它們不是資源句柄)。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#discussion-never-throw-while-holding-a-resource-not-owned-by-a-handle
新書介紹
《實戰Python設計模式》是作者最近出版的新書,拜托多多關注!
本書利用Python 的標準GUI 工具包tkinter,通過可執行的示例對23 個設計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟件開發工作中每個設計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,并合理運用設計模式。
對設計模式感興趣而且希望隨學隨用的讀者通過本書可以快速跨越從理解到運用的門檻;希望學習Python GUI 編程的讀者可以將本書中的示例作為設計和開發的參考;使用Python 語言進行圖像分析、數據處理工作的讀者可以直接以本書中的示例為基礎,迅速構建自己的系統架構。
覺得本文有幫助?請分享給更多人。
關注微信公眾號【面向對象思考】輕松學習每一天!
面向對象開發,面向對象思考!
總結
以上是生活随笔為你收集整理的c++ file* 句柄泄漏_C++核心准则?讨论:持有没有被句柄管理的资源时切勿抛出异常...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华科大有宿舍遭遇雷击?校方辟谣:天花板松
- 下一篇: WebClient UI MVC dat