迭代器与const迭代器之间的比较是否低效?

11

变量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上导致隐式转换吗?

(由于在for循环内部多次使用end,所以我想将其提升出来。)


@David 在我这个特定的情况中,它是一个std::string,但我一般很好奇。 - fredoverflow
1个回答

12

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

实际上,iteratorconst_iterator 很可能参与继承关系(其中一个从另一个派生,或者两个都从一个 _iterator_base 派生),因此不需要进行隐式转换(相反,更派生的迭代器将被忽略)。即使在没有这些情况下,转换也很可能足够简单,可以被内联和优化。

libstdc++ 通过在 iteratorconst_iterator 之间定义 operator==operator!= 来优化这些比较: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 - 尽管再次强调,从 iteratorconst_iterator 的构造函数如此微不足道,以至于我预计它将被完全优化掉。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接