警告 C26817

範囲 for ループの変数 のコピーの負荷が高い可能性があります。 const 参照 (es.71) にすることを検討してください。

詳細については、C++ Core Guidelines にある 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 以外の参照を使用すると、参照を誤って使用してコンテナーの要素を変更する可能性があります。 ローカル ループ変数のみを変更する必要がある場合、負荷が高くなる恐れのあるコピーは回避できません。