将 std::vector 附加到自身,未定义的行为?

2021-12-21 00:00:00 language-lawyer vector c++

这个问题让我不确定向自身附加一个向量.所以问题是:以下代码行符合我的预期,但是否符合标准?

This question made me uncertain about appending a vector to itself. So the question is: Following lines of code do what I expect, but is it standard conform?

vec.reserve(vec.size() * 2):
vec.insert(vec.end(), vec.begin(), vec.end());

以下(没有reserve())仍然有效,是否符合标准?

Following (without reserve()) still works, is it even standard conform?

vec.insert(vec.end(), vec.begin(), vec.end());

还是取决于实现?

推荐答案

根据 C++03 ISO 规范(§23.1.1,表 67)(以及@AndyProwl 在 §23.2.3 中提到的, C++11 ISO 规范的表 11),作为序列要求的一部分,序列容器中的操作 a.insert(p, i, j) 具有以下前提条件:

According to the C++03 ISO spec (§23.1.1, Table 67) (and as @AndyProwl has mentioned, in §23.2.3, table 11 of the C++11 ISO spec), as part of sequence requirements, the operation a.insert(p, i, j) in a sequence container has this precondition:

ij 不是a 的迭代器.

换句话说,允许序列容器安全地假设,如果您执行范围插入操作,则该范围将不会从原始容器上的迭代器中定义.

In other words, sequence containers are allowed to safely assume that if you do a range insertion operation, that range will not be defined from iterators over that original container.

因此,如果您尝试将容器的元素插入到自身中,您就是在调用标准库函数并破坏了前提条件.这会导致未定义的行为,这意味着如果库实现者是好人,它可能在某些平台上工作,但它可能会在没有任何理由的情况下发生可怕的灾难性失败.

As a result, if you try to insert a container's elements into itself, you are calling a standard library function and breaking a precondition. This results in undefined behavior, meaning that it might work on some platforms if the library implementers are nice people, but it could terribly and catastrophically fail with no justification.

希望这有帮助!

相关文章