Re: std::vector::reserve()
The assert is correct even if reserve is used. All reserve() does is to allocate memory (which MSVC does). It doesn't add any elements. If you just reserve and don't add any elements, then .size() will be zero and hence accessing [0] is undefined behaviour (which can change between compilers). The capacity of a vector is different to its size. The only criteria is that capacity() >= size(). The difference between capacity() and size() is the number of elements that can be pushed on to the vector without memory re-allocation happening. Using .reserve() just prevents re-allocation until that number of elements have been added. resize() allocates memory as needed and sets .size() to the given size. Only elements from 0 to .size() - 1 are accessible. Elements from .size() to capacity() - 1 are not accessible. Consider:
Code:
std::vector<int> vect;
vect.reserve(3);
int* contents = vect.empty() ? nullptr : &vect[0];
If you always want [0] to exist, then you need to re(size) rather than reserve.
Code:
std::vector<int> vect;
vect.resize(3);
int* contents = &vect[0]; // now OK as has 3 elements
or
Code:
std::vector<int> vect(3);
int* contents = &vect[0]; // now OK as has 3 elements
1 Attachment(s)
Re: std::vector::reserve()
Re: std::vector::reserve()
John, please don't ask different questions in the same post. It's better to start a new post for each new question.