c++std-filesystemreverse-iterator

No reverse iterators for `std::filesystem::path`?


Is there a technical reason why std::filesystem::path doesn't offer reverse iterators (i.e., rbegin and rend)?

If I have a std::filesystem::path for /a/b/c/b/d/b/e and I want to find the first component that matches b, I can use std::find(p.begin(), p.end(), fs::path("b")).

But if I want to find the last component that matches b, I can't just switch to reverse iterators. I can write my own loop, but it seems like this would be a common operation that would have been "almost free" to implement.

Is there something about the design of the interface that would make it difficult to provide reverse iterators?


Solution

  • According to this page of cppreference.com:

    "std::reverse_iterator does not work with iterators whose dereference returns a reference to a member of *this (so-called "stashing iterators"). An example of a stashing iterator is std::filesystem::path::iterator."

    Also from a page of boost.org, which says:

    Path iterators store their value objects internally and when dereferenced return references to those internal objects. They cannot be used with iterator adaptors such as std::reverse_iterator that assume references obtained by dereferencing an iterator point to objects that out-live the iterator itself.

    To find a more detailed explanation on stashing iterators, visit this page.