Consider following code:
vector<uint8_t> v(1);
v.reserve(2);
uint8_t *data = &v.front();
data[1] = 0;
Is there undefined behavior (C++98, C++03, C++11)?
And if yes, what is best way to get RAII buffer (not using C++11)?
Consider following code:
vector<uint8_t> v(1);
v.reserve(2);
uint8_t *data = &v.front();
data[1] = 0;
Is there undefined behavior (C++98, C++03, C++11)?
And if yes, what is best way to get RAII buffer (not using C++11)?
It is undefined behaviour to call v.front()
whenever v.empty()
is true. It is undefined behaviour to call v[n]
unless n < v.size()
. Moreover, there are no objects at the reserved memory, so you cannot treat the memory as if it was an object. A vector only guranatees
that
[data(), data() + size())
is a valid range
and there are no guarantees that there is any larger valid range. (Note that data() == &front()
, so this is applies to your code.)
I have checked C++98 standard.
Here is note for reserve():
"It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve()."
And from note for "vector modifiers":
"If no reallocation happens, all the iterators and references before the insertion point remain valid."
Therefore IMHO code presented in question is perfectly valid even for C++98.