C++核心準則:R.13: 在一個表達式中最多隻執行一次顯式資源分配

C++核心準則:R.13: 在一個表達式中最多隻執行一次顯式資源分配

R.13: Perform at most one explicit resource allocation in a single expression statement

R.13: 在一個表達式中最多隻執行一次顯式資源分配

Reason(原因)

If you perform two explicit resource allocations in one statement, you could leak resources because the order of evaluation of many subexpressions, including function arguments, is unspecified.

如果你在一個表達式中執行兩次(或以上的)資源分配,由於包括函數參數在內的子表達式的執行順序是沒有定義的,因此可能導致資源洩露。

Example(示例)

<code>void fun(shared_ptr<widget> sp1, shared_ptr<widget> sp2);/<widget>/<widget>/<code>

This fun can be called like this:

函數可能被這樣調用:

<code>// BAD: potential leak
fun(shared_ptr<widget>(new Widget(a, b)), shared_ptr<widget>(new Widget(c, d)));/<widget>/<widget>/<code>

This is exception-unsafe because the compiler may reorder the two expressions building the function's two arguments. In particular, the compiler can interleave execution of the two expressions: Memory allocation (by calling operator new) could be done first for both objects, followed by attempts to call the two Widget constructors. If one of the constructor calls throws an exception, then the other object's memory will never be released!

因為編譯器可能會調整構建函數參數的兩個表達式的執行順序,這段代碼在發生異常時會出問題。通常,編譯器會交錯執行兩個表達式:(使用new進行)兩個對象的內存分配可能首先進行,接下來調用兩個Widget的構造函數。如果一個調用某個構造函數是拋出異常,那麼另一個就永遠不會被釋放。

This subtle problem has a simple solution: Never perform more than one explicit resource allocation in a single expression statement. For example:

這個不易察覺的問題有一個簡單的解決方案:永遠不在一個表達式中執行兩次(含兩次)以上的顯式資源分配。例如:

<code>shared_ptr<widget> sp1(new Widget(a, b)); // Better, but messy
fun(sp1, new Widget(c, d));/<widget>/<code>

The best solution is to avoid explicit allocation entirely use factory functions that return owning objects:

最好的解決方案是使用返回管理對象的工廠方法徹底避免顯式資源分配。

<code>fun(make_shared<widget>(a, b), make_shared<widget>(c, d)); // Best/<widget>/<widget>/<code>

Write your own factory wrapper if there is not one already.

如果目前還不存在,那就自己寫工廠包裝類。

Enforcement(實施建議)

  • Flag expressions with multiple explicit resource allocations (problem: how many direct resource allocations can we recognize?)
  • 標記具有多個顯式分配資源的表達式(問題是:我們可以識別出多少顯式分配資源的情況?)

原文鏈接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r13-perform-at-most-one-explicit-resource-allocation-in-a-single-expression-statement


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

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

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


分享到:


相關文章: