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:
下面的示例是非效率的(因為它包含了不需要的分配和釋放動作),容易拋出異常並且從...部分返回的話會發生內存洩露,而且冗長。
<code>void f(int n)
{
auto p = new Gadget{n};
// ...
delete p;
}/<code>
Instead, use a local variable:
作為代替,使用局部變量:
<code>void f(int n)
{
Gadget g{n};
// ...
}/<code>
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
覺得本文有幫助?請分享給更多人。
關注【面向對象思考】輕鬆學習每一天!
面向對象開發,面向對象思考!
閱讀更多 面向對象思考 的文章