变种a:
const auto end = whatever.end();
for (auto it = whatever.begin(); it != end; ++it)
{
// ...
}
变式b:
const auto end = whatever.cend(); // note the call to cend insteand of end here
for (auto it = whatever.begin(); it != end; ++it)
{
// ...
}
有没有理由相信变量b的效率低于变量a,因为循环条件比较了两种不同的迭代器?这是否会导致隐式转换 it
?
(end
在for循环中多次使用,因此我希望将其提升。)
原则上,它可能效率较低,并导致非零成本的隐式转换。
在实践中, iterator
和 const_iterator
很可能参与继承关系(一个来自另一个,或两者都来自一个 _iterator_base
)这样不等式运算符在基类上定义,并且不需要隐式转换(相反,更多派生的迭代器被忽略)。即使没有这些,转换也可能非常简单,无法进行内联和优化。
通过定义,libstdc ++以不同方式优化这些比较 operator==
和 operator!=
之间 iterator
和 const_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_iterator
从 iterator
是如此微不足道,我希望它能够完全优化。