5

Is the following code valid and well-defined?

auto start = std::string::const_iterator();
auto end = std::string::const_iterator();

auto output = std::string(start, end);

(The expected output being an empty string.)

user673679
  • 1,327
  • 1
  • 16
  • 35
  • Possible duplicate of [What is an iterator's default value?](https://stackoverflow.com/questions/3395180/what-is-an-iterators-default-value) – apple apple May 07 '19 at 12:19
  • 1
    I guess there is no guarantee two default constructed (if possible) iterator should compare equal. – apple apple May 07 '19 at 12:20

1 Answers1

8

According to cppreference.com, a random access iterator, of which a string iterator is one, meets all requirements of a bidirectional iterator.

Furthermore, a bidirectional iterator meets all requirements of a forward iterator.

Finally, since C++14, a forward iterator can be value-initialized, and will compare equal to all other value-initialized forward iterators of the same type:

A value-initialized LegacyForwardIterator behaves like the past-the-end iterator of some unspecified empty container: it compares equal to all value-initialized LegacyForwardIterators of the same type.

Based on that, I believe this is well-defined at least as of C++14.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148