将空范围(相同的迭代器)传递给 STL 算法是否会导致定义的行为?
考虑以下问题:
std::vector<int> vec(1); // vector has one element
std::fill(vec.begin(), vec.begin(), 42);
std::fill(vec.begin()+1, vec.end(), 43);
std::fill(vec.end(), vec.end(), 44);
上面的所有 std::fill
用法都会导致定义的行为吗?我能保证 vec 不会被修改吗?我倾向于认为“是”,但我想确保标准允许这种用法。
Consider the following:
std::vector<int> vec(1); // vector has one element
std::fill(vec.begin(), vec.begin(), 42);
std::fill(vec.begin()+1, vec.end(), 43);
std::fill(vec.end(), vec.end(), 44);
Will all of the std::fill
usages above result in defined behavior? Am I guaranteed that vec will remain unmodified? I'm inclined to think "yes", but I want to make sure the standard allows such usage.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管我不认为标准中明确禁止它,但我会说不。该标准要求迭代器范围的类型为
[first, last)
,其中包括first
以及直到但不包括last
的所有内容。为first
和last
传递相同的值对于此定义没有逻辑意义,因为它既包含又不包含,所以我希望得到未定义的行为后退。编辑:
清理了我最初的回复,并添加了以下内容:在温习了我的数学区间符号,我发现
[x,x)
形式的区间被定义为空集。所以我上面的答案是错误的——我不希望得到未定义的行为。Although I don't believe it's specifically forbidden in the standard, I would say no. The standard requires that iterator ranges be of type
[first, last)
which includesfirst
and everything up to but not includinglast
. Passing in the same value forfirst
andlast
doesn't make logical sense with this definition as it would be both included and not included, so I would expect to get undefined behavior back.EDIT:
Cleaned up my initial response, and adding this: after brushing up on my mathematical interval notation, I've discovered that an interval of the form
[x,x)
is defined as the empty set. So my above answer is wrong -- I would NOT expect to get undefined behavior.不,如果不会导致未定义的行为。
该标准在 24.1/7 中定义了空迭代器范围,但没有任何地方表明向
std::fill
算法提供空范围会导致未定义的行为。这实际上是人们对经过深思熟虑的实施所期望的结果。对于自然处理空范围的算法,对调用者强加检查空范围的要求将是一个严重的设计错误。
No, if doesn't cause undefined behavior.
The standard defines empty iterator range in 24.1/7 and nowhere it says that supplying an empty range to
std::fill
algorithm causes undefined behavior.This is actually what one would expect from a well-thought through implementation. With algorithms that handle emtpy range naturally, imposing the requirement to check for empty range on the caller would be a serious design error.