range-for 循环中可能存在成本高昂的 name 变量副本。 请考虑使其成为常量引用 (es.71)。
有关详细信息,请参阅ES.71:在C++核心准则中进行选择时,建议使用range-for
-statement而不是for
-statement。
示例
如果 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
// ...
}
}
警告忽略了一些复制成本低的类型,例如标量(指针、算术类型等)。
若要解决此问题,如果此循环变量没有在循环中的任何位置发生转变,则可使其成为常量引用:
#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
关键字使循环变量不可变。 使用非常量引用可能会无意中使用该引用来修改容器的元素。 如果只想修改局部循环变量,则可能会不可避免地出现成本高昂的复制。