C++核心準則R.5: 範圍對象不要在堆內存上構建

R.5: Prefer scoped objects, don't heap-allocate unnecessarily

R.5: 範圍對象不要在堆內存上構建

 

Reason(原因)

A scoped object is a local object, a global object, or a member. This implies that there is no separate allocation and deallocation cost in excess of that already used for the containing scope or object. The members of a scoped object are themselves scoped and the scoped object's constructor and destructor manage the members' lifetimes.

範圍對象可以是局部對象,全局對象或者成員。這意味着不存在包含該對象的範圍或者對象的另外的分配和釋放成本。範圍對象的成員自身就是範圍,它們的構造函數和析構函數管理對象的生命週期。

 

Example(示例)

The following example is inefficient (because it has unnecessary allocation and deallocation), vulnerable to exception throws and returns in the ... part (leading to leaks), and verbose:

下面的示例是非效率的(因爲它包含了不需要的分配和釋放動作),容易拋出異常並且從...部分返回的話會發生內存泄露,而且冗長。

void f(int n)
{
    auto p = new Gadget{n};
    // ...
    delete p;
}

Instead, use a local variable:

作爲代替,使用局部變量:

void f(int n)
{
    Gadget g{n};
    // ...
}

Enforcement(實施建議)

  • (Moderate) Warn if an object is allocated and then deallocated on all paths within a function. Suggest it should be a local auto stack object instead.

  • (中等)如果在同一個函數內部,一個對象被分配之後在所有路徑上釋放它,報警。建議使用局部自動堆棧上的對象。

  • (Simple) Warn if a local Unique_pointer or Shared_pointer is not moved, copied, reassigned or reset before its lifetime ends.

  • (簡單)如果局部的unique指針或者shared指針在生命週期結束之前沒有被移動,拷貝,重新賦值或者reset,報警。

     

原文鏈接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r5-prefer-scoped-objects-dont-heap-allocate-unnecessarily

 


 

覺得本文有幫助?歡迎點贊並分享給更多的人。

閱讀更多更新文章,請關注微信公衆號【面向對象思考】

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章