경고 C26817

range-for 루프에서 변수 이름의 잠재적으로 비용이 많이 드는 복사본입니다. const 참조(es.71)로 만드는 것이 좋습니다.

자세한 내용은 C++ 핵심 지침의 ES.71 노트 를 참조하세요.

예시

range-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 키워드(keyword) 루프 변수를 변경할 수 없게 만듭니다. 비 const 참조를 사용하면 실수로 참조를 사용하여 컨테이너의 요소를 수정할 수 있습니다. 로컬 루프 변수만 수정해야 하는 경우 잠재적으로 비용이 많이 드는 복사는 피할 수 없습니다.