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?
vector::reserve does allocate memory, so your question about reserving memory without allocating is incorrect.
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.
vector::reserve reserve() does not change the size of the vector.
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.
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.
Is
reserve
forced to updatedata
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())
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With