I have a function which takes an int * and modifies the array that is passed in. I know ahead of time how many elements it will access. Let’s say that’s m values.
What will happen if I call reserve(m) on a vector<int> then send the pointer data() to the function?
My guess is that doing this might work if I subsequently access the data as though it were an array, from the pointer, but if I were to try to retrieve this data from the vector using operator [] the size of the vector will not have been updated, and I will have issues. So I should just use resize(m) to do this.
Don’t do it; it’s undefined behaviour and simply not allowed. Instead, you should do the almost equally expensive
resize()operation and then pass thedata()pointer.The only added cost comes from the zeroing out of the memory. Unfortunately there is no standard library container that handles uninitialized dynamic storage short of a
std::unique_ptr<int[]>(new int[m]). The cost of the zeroing out is very small, though (but it may be conceptually annoying because you know that you are going to overwrite the data). I guess in a high-performance context you could give the unique-pointer approach a try. (Note that array-new[]for fundamental types is typically entirely equivalent to::operator new()ormalloc()).