C++核心準則R.12:立即將顯式分配的資源交給資源管理對象​

C++核心準則R.12:立即將顯式分配的資源交給資源管理對象​

R.12: Immediately give the result of an explicit resource allocation to a manager object

R.12:立即將顯式分配的資源交給資源管理對象

Reason(原因)

If you don't, an exception or a return may lead to a leak.

如果不這樣做,發生異常或者返回操作時可能會引發洩露。

Example, bad(反面示例)

<code>void f(const string& name)
{
FILE* f = fopen(name, "r"); // open the file
vector<char> buf(1024);
auto _ = finally([f] { fclose(f); }); // remember to close the file
// ...
}/<char>/<code>

The allocation of buf may fail and leak the file handle.

如果分配buffer失敗(拋出異常,譯者注)就會導致文件句柄的洩露。

Example(示例)

<code>void f(const string& name)
{
ifstream f{name}; // open the file
vector<char> buf(1024);

// ...
}/<char>/<code>

The use of the file handle (in ifstream) is simple, efficient, and safe.

(使用ifstream管理)文件句柄的用法簡單、高效而且安全。

Enforcement(實施建議)

  • Flag explicit allocations used to initialize pointers (problem: how many direct resource allocations can we recognize?)
  • 標記使用顯式分配的資源初始化指針的情況(問題是:我們能夠識別出多少直接分配資源的情況?)

原文鏈接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r12-immediately-give-the-result-of-an-explicit-resource-allocation-to-a-manager-object


覺得本文有幫助?請分享給更多人。

關注【面向對象思考】輕鬆學習每一天!

面向對象開發,面向對象思考!


分享到:


相關文章: