Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use std::vector::data after reserve

I have a std::vector on which I call reserve with a large value. Afterwards I retrieve data().

Since iterating data is then crashing I am wondering whether this is even allowed. Is reserve forced to update data to the allocated memory range?

like image 756
abergmeier Avatar asked Aug 16 '16 10:08

abergmeier


People also ask

Does vector Reserve take up memory?

vector::reserve does allocate memory, so your question about reserving memory without allocating is incorrect.

What does std::vector Reserve do?

std::vector class provides a useful function reserve which helps user specify the minimum size of the vector.It indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory.

Does Reserve change vector size?

vector::reserve reserve() does not change the size of the vector.

What does .reserve do in C++?

The reserve() function in CPP is a very useful function of the vector library. It helps in allocating space and reserving it. We can use the two variables size and capacity which will denote the number of elements and the maximum number of elements that can be stored in that vector.


2 Answers

The guarantee of reserve is that subsequent insertions do not reallocate, and thus do not cause invalidation. That's it. There are no further guarantees.

like image 85
Kerrek SB Avatar answered Sep 17 '22 17:09

Kerrek SB


Is reserve forced to update data to the allocated memory range?

No. The standard only guarantees that std::vector::data returns a pointer and [data(), data() + size()) is a valid range, the capacity is not concerned.

§23.3.11.4/1 vector data [vector.data]:

Returns: A pointer such that [data(), data() + size()) is a valid range. For a non-empty vector, data() == addressof(front()).

like image 43
songyuanyao Avatar answered Sep 21 '22 17:09

songyuanyao