-3

What does vector::reserve actually do since trying to access its data is an error?

vector<int> v.reserve(10);
v[4] = 22;

if this allocated space it shouldn't be an error in the first place.. how can it 'reserve' space if it doesn't even allocate it? How can the OS be informed that it has to allocate space for the vector?

Dean
  • 6,610
  • 6
  • 40
  • 90

2 Answers2

6

reserve reserves memory for growing the vector, with out changing it's size(). So in your case, [4] is still an invalid index.

While the vector will grow to a size as needed, there's a significant tradeoff between growing in large vs. small chunks: large chunks make expensive reallocations and copies less common, but also waste memory.

reserve(10) reserves memory so you can e.g. push_back 10 elements without having a reallocation.


When to use: if you are adding elements to a vector in multiple steps, and you know ahead the amount of elements - or even if you have a good guess - use reserve to prepare the vector for accepting that many elements, and reduce the number of allocations necessary.

The amount reserved is called capacity - and can be queried using .capacity().

peterchen
  • 40,917
  • 20
  • 104
  • 186
  • I'm tempted to say that it does almost nothing. It gives certain guarantees about iterator invalidation, and may affect the performance of the program, but `reserve` it self doesn't have any noticeable side effects. – Aaron McDaid Nov 09 '15 at 10:11
  • @Dean: No. Reserve always allocates contiguous memory, never anything else. – Benjamin Lindley Nov 09 '15 at 10:16
  • Oh.. so is it writing to my_vector[4] still an error even for non-object types like int? (things that don't require construction) – Dean Nov 09 '15 at 10:17
  • @Dean: yes. the object is neither constructed nor accessible. Note that `.at(index)` is range-checked, so an invalid index throws an exception. for `operator[]`, an invalid index is **undefined behavior** (even though implementations might not mind after a reserve) – peterchen Nov 09 '15 at 11:09
  • @AaronMcDaid: Well... IIRC it is guaranteed that growing to `size<=capacity` (e.g. by inserting or appending) will not invalidate existing iterators, which is a big thing. Furthermore, performance is observably affected - both in terms of Big-O and wall time. OTOH, yeah, I see where you are coming from. – peterchen Jan 28 '16 at 10:32
0

vector::reserve allocate the memory but the size of the vector not change (even if the size of reserve < current size of the vector). Use vector::resize for allocate and change the size.

Jerome
  • 529
  • 4
  • 14