Is incrementing std::string::end() iterator undefined?

Viewed 122

Is it "legal" to increment the end iterator of a std::string in order to include the null-terminator in the range?

For example

std::string my_text{"Arbitrary string"};
std::vector<std::uint8_t> my_collection{};
my_collection.insert(my_collection.end(), std::begin(my_text), std::next(std::end(my_text)));

The reason I ask is that I'd just prefer to avoid the pointer arithmetic involved in my_text.c_str() + my_text.size() (or is it my_text.size()+1?).

I'm reasonably confident that most implementations today would behave as expected. Still, answers which include C++-legalese for the language lawyers among us are appreciated. Just so I have an airtight defense if I'm ever in C++ court.

1 Answers

I would expect that incrementing the end iterator implies undefined behaviour, but I dont find a reference for.

But I have a reference that the dereferenciation of end is undefined behaviour: https://en.cppreference.com/w/cpp/string/basic_string/end

So the standard doesn't ensure that anything expected happen if you do so.

Related