C++核心准则ES.12:不要在嵌套作用域中重复使用同样的名称

2020-04-24 17:40:26 浏览数 (2)

ES.12: Do not reuse names in nested scopes

ES.12: 不要在嵌套作用域中重复使用同样的名称

Reason(原因)

It is easy to get confused about which variable is used. Can cause maintenance problems.

这会导致更难弄清楚到底哪个变量在使用。可能引起维护问题。

Example, bad(反面示例)

代码语言:javascript复制
int d = 0;
// ...
if (cond) {
    // ...
    d = 9;
    // ...
}
else {
    // ...
    int d = 7;
    // ...
    d = value_to_be_returned;
    // ...
}

return d;

If this is a large if-statement, it is easy to overlook that a new d has been introduced in the inner scope. This is a known source of bugs. Sometimes such reuse of a name in an inner scope is called "shadowing".

这一个很大的if语句,很容易漏掉内部作用域引入了一个新变量d这个事实。这是有名的错误源之一。这种在内部作用域中重用名称的做法被称为“遮盖”。

Note(注意)

Shadowing is primarily a problem when functions are too large and too complex.

“遮盖”主要是在函数太大或者过于复杂时发生问题。

Example(示例)

Shadowing of function arguments in the outermost block is disallowed by the language:

处于最外侧的函数参数的遮盖问题是被语言禁止的。

代码语言:javascript复制
void f(int x)
{
    int x = 4;  // error: reuse of function argument name

    if (x) {
        int x = 7;  // allowed, but bad
        // ...
    }
}
Example, bad(反面示例)

Reuse of a member name as a local variable can also be a problem:

重用成员名称作为局部变量同样会引起问题:

代码语言:javascript复制
struct S {
    int m;
    void f(int x);
};

void S::f(int x)
{
    m = 7;    // assign to member
    if (x) {
        int m = 9;
        // ...
        m = 99; // assign to local variable
        // ...
    }
}
Exception(例外)

We often reuse function names from a base class in a derived class:

我们经常在派生类中重用基类的函数名:

代码语言:javascript复制
struct B {
    void f(int);
};

struct D : B {
    void f(double);
    using B::f;
};

This is error-prone. For example, had we forgotten the using declaration, a call d.f(1) would not have found the int version of f.

这容易引发错误。例如,如果我们忘记using声明,调用d.f(1)时就无法发现f函数的整数版本。

??? Do we need a specific rule about shadowing/hiding in class hierarchies?

我们是否需要定义一个特别的适用于类继承情况下的遮盖/隐藏规则?

Enforcement(实施建议)

  • Flag reuse of a name in nested local scopes
  • 标记嵌套作用域中的名称重用。
  • Flag reuse of a member name as a local variable in a member function
  • 标记使用成员名称定义局部变量的情况。
  • Flag reuse of a global name as a local variable or a member name
  • 标记使用全局名称定义局部变量和成员名称的情况。
  • Flag reuse of a base class member name in a derived class (except for function names)
  • 标记派生类中重用基类名称的情况(函数名称除外)

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es12-do-not-reuse-names-in-nested-scopes

0 人点赞