递增 std::string::end() 迭代器是否未定义?

问题描述

增加 endstd::string 迭代器以在范围内包含空终止符是否“合法”?

例如

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)));

我问的原因是我更愿意避免my_text.c_str() + my_text.size()(或者是my_text.size()+1?)中涉及的指针算术。

我有理由相信今天的大多数实现都会按预期运行。尽管如此,对于我们中间的语言律师来说,包括 C++-legalese 的答案还是值得赞赏的。如果我在 C++ 法庭上,我有一个严密的防御。

解决方法

我希望增加结束迭代器意味着未定义的行为,但我没有找到参考。

但我有一个参考,即 end 的取消引用是未定义的行为: https://en.cppreference.com/w/cpp/string/basic_string/end

因此,如果您这样做,标准并不能确保任何预期的事情都会发生。