问题
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?
回答1:
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.
回答2:
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())
.
回答3:
There is no requirement that data()
returns dereferencable pointer for empty (size() == 0
) vector, even if it has nonzero capacity. It might return nullptr
or some arbitrary value (only requirement in this case is that it should be able to be compared with itself and 0 could be added to it without invoking UB).
回答4:
I'd say the documentation is pretty clear on this topic: anything after data() + size()
may be allocated but not initialized memory: if you want to also initialize this memory you should use vector::resize
.
void reserve (size_type n);
Request a change in capacity
Requests that the vector capacity be at least enough to contain n elements.
If n is greater than the current vector capacity, the function causes the container to reallocate its storage increasing its capacity to n (or greater).
In all other cases, the function call does not cause a reallocation and the vector capacity is not affected.
This function has no effect on the vector size and cannot alter its elements.
I'm not sure why you would want to access anything after data() + size()
after reserve()
in the first place: the intended use of reserve()
is to prevent unnecessary reallocations when you know or can estimate the expected size of your container, but at the same time avoid the unnecessary initializon of memory which may be either inefficient or impractical (e.g. non-trivial data for initialization is not available). In this situation you could replace log(N)
reallocations and copies with only 1 improving performance.
来源:https://stackoverflow.com/questions/38972443/use-stdvectordata-after-reserve