【发布时间】:2016-03-28 10:11:46
【问题描述】:
在Deduce type of template type in C++ 跟进我自己的问题,有些人提到通过引用传递iterators 不是惯用的,并且在给定的用例中它不起作用:
template <typename Iter> iterate(Iter &first, Iter &last)
{
// Do something with the iterators
}
iterate(container.begin(), container.end()); // error, binding non-const ref to rvalue!
深入研究后,我发现(至少)另外两个涵盖前者的主题:
- What's wrong with passing C++ iterator by reference?
- Why do C++ STL container begin and end functions return iterators by value rather than by constant reference?
但是对于通过右值引用 && 传递迭代器是否会(甚至)比通过值传递它们更好,似乎没有问题/答案。如
template <typename Iter> iterate(Iter &&first, Iter &&last)
{
// Do something with the iterators
}
iterate(container.begin(), container.end());
我的代码使用右值引用编译并运行良好,因此我对此的想法。
【问题讨论】:
-
此上下文中的右值引用称为转发引用,也称为通用引用。
-
大多数迭代器都非常小(例如,单个指针)。通过引用传递它们没有任何(性能)优势,并且如果您必须适应左值和右值引用,它会使您的代码更加复杂。