But why does this not cause a
segfault?
Because the stars aligned. Or you were running in debug and the compiler did something to "help" you. Bottom line is you're doing the wrong thing, and crossed over in to the dark and nondeterministic world of Undefined Behavior. You reserve
one spot in the vector and then try to cram 5 elements in to the reserve
-ed space. Bad.
You have 3 options. In my personal order of preference:
1) Use a back_insert_iterator
which is designed for just this purpose. It is provided by #include <iterator>
. The syntax is a bit funky, but fortunately a nice sugar-coated shortcut, back_inserter
is also provided:
#include <iterator>
// ...
copy( p, p+5, back_inserter(v) );
2) assign
the elements to the vector. I prefer this method slightly less simply because assign
is a member of vector
, and that strikes me as slightly less generic than using somethign from algorithm
.
v.assign(p, p+5);
3) reserve
the right number of elements, then copy them. I consider this to be a last ditch effort in case everything else fails for whatever reason. It relies on the fact that a vector
's storage is contiguous so it's not generic, and it just feels like a back-door method of getting the data in to the vector
.