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};
// ...
}
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r5-prefer-scoped-objects-dont-heap-allocate-unnecessarily