15

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

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

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

Or implementation depending?

Community
  • 1
  • 1
Christian Ammer
  • 7,464
  • 6
  • 51
  • 108

1 Answers1

17

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:

i, j are not iterators into 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.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • @AndyProwl- Thanks! Out of curiosity, is there an easy way to get a legal copy of that ISO spec? – templatetypedef Feb 09 '13 at 22:15
  • @templatedtypdef: Yes, but you have to pay for it. Or you can get a draft for free from [here](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2012/n3485.pdf). – Andy Prowl Feb 09 '13 at 22:16
  • @AndyProwl: That's a very recent draft, with substantial post-C++11 changes. N3337 is much more like the actual C++11 standard, with only minor editorial changes. – Nicol Bolas Feb 09 '13 at 22:17
  • Yes, this helps a lot, thanks for the standard reference and the explaining words! I was so sure that the `resize()` example is correct, ouch. – Christian Ammer Feb 09 '13 at 22:19
  • @NicolBolas: Thank you for the information. Where can I find a link to that draft? – Andy Prowl Feb 09 '13 at 22:21