迭代器和const_iterator之间的比较是否效率低下?

fre*_*low 11 c++ performance iterator const c++11

变种a:

const auto end = whatever.end();
for (auto it = whatever.begin(); it != end; ++it)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

变式b:

const auto end = whatever.cend(); // note the call to cend insteand of end here
for (auto it = whatever.begin(); it != end; ++it)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

有没有理由相信变量b的效率低于变量a,因为循环条件比较了两种不同类型的迭代器?这会导致隐式转换it吗?

(end在for循环中多次使用,因此我希望将其提升.)

eca*_*mur 12

原则上,它可能效率较低,并导致非零成本的隐式转换.

在实践中,iterator并且const_iterator可能参与继承关系(一个派生自另一个,或者两者派生自一个_iterator_base),以便在基类上定义不等运算符,并且不需要隐式转换(相反,更多派生的迭代器被忽略).即使没有这些,转换也可能非常简单,无法进行内联和优化.

的libstdc ++不同优化这些比较,通过定义operator==operator!=之间iteratorconst_iterator:http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a02037.html#l00295

libc ++没有任何优化:http://llvm.org/svn/llvm-project/libcxx/trunk/include/__tree - 虽然const_iteratorfrom 的构造函数iterator是如此微不足道,我希望它完全被优化出来.