C++核心准则R.5: 范围对象不要在堆内存上构建​

2020-03-27 17:10:38 浏览数 (2)

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:

下面的示例是非效率的(因为它包含了不需要的分配和释放动作),容易抛出异常并且从...部分返回的话会发生内存泄露,而且冗长。

代码语言:javascript复制
void f(int n)
{
    auto p = new Gadget{n};
    // ...
    delete p;
}

Instead, use a local variable:

作为代替,使用局部变量:

代码语言:javascript复制
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

0 人点赞