Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do the new ranges remove_* algorithms *move* the `first` pointer?

I was reading through the MSVC STL implementation of std::ranges::remove when I noticed the following line:

_First = _RANGES _Find_if_unchecked(_STD move(_First), _Last, _Pred, _Proj);

Indeed, cppreference has the following line in their ‘possible implementation’ too:

first = ranges::find_if(std::move(first), last, pred, proj);

What’s confusing to me is, I’ve just about never seen anyone move an iterator; they’re typically cheap to copy (or at least should be), and even if this were an issue of copies, we could take a universal reference and std::forward the iterator to find_if instead surely?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What advantage does casting to an rvalue reference have here over simply passing by value?

>Solution :

ranges::find accepts input_iterator, which is not necessarily copyable ((an example in the standard is basic_istream_view::iterator).

In the C++20 iterator system, only iterators that model forward_iterator are guaranteed to be copyable, so std::move is necessary here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading