警告 C26817

範圍 for 迴圈中變數 名稱 的可能昂貴複本。 請考慮將其設定為常值參考 (es.71)。

如需詳細資訊,請參閱 C++ 核心指導方針中的 ES.71 附注

範例

如果範圍 for 迴圈變數未明確標示為參考,則會取得逐一查看的每個元素複本:

#include <vector>

class MyComplexType {
    int native_array[1000];
    // ...
};

void expensive_function(std::vector<MyComplexType>& complex_vector_ref)
{
    for (auto item: complex_vector_ref) // Warning: C26817
    {
        // At each iteration, item gets a copy of the next element
        // ...
    }
    for (MyComplexType item: complex_vector_ref)
    {
        // It happens whether you use the auto keyword or the type name
        // ...
    }
}

警告會忽略某些價格便宜的類型,例如純量複製(指標、算術類型等等)。

若要修正此問題,如果迴圈變數未在迴圈中的任何位置變動,請將其設為 const 參考:

#include <vector>

class MyComplexType {
    int native_array[1000];
    // ...
};

void less_expensive_function(std::vector<MyComplexType>& complex_vector_ref)
{
    for (const auto& item: complex_vector_ref)
    {
        // item no longer gets a copy of each iterated element
        // ...
    }
    for (const MyComplexType& item: complex_vector_ref)
    {
        // item no longer gets a copy of each iterated element
        // ...
    }
}

關鍵字 const 會讓迴圈變數不可變。 使用非 const 參考可讓您不小心使用 參考來修改容器的元素。 如果您只需要修改本機迴圈變數,則可能耗費資源的複製是不可避免的。