C++核心準則ES.12:不要在嵌套作用域中重複使用同樣的名稱

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(反面示例)

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:

處於最外側的函數參數的遮蓋問題是被語言禁止的。

 

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:

重用成員名稱作爲局部變量同樣會引起問題:

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:

我們經常在派生類中重用基類的函數名:

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

 


 

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

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

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