I have a std::vector of values for which I know the maximum size, but the actual size will vary during usage:
void setupBuffer(const size_t maxSize) {
myVector.reserve(maxSize);
}
void addToBuffer(const Value& v) {
myVector.push_back(v);
if (myVector.size() == maxSize) {
// process data...
myVector.clear();
}
}
However, in setupBuffer, I need to obtain a pointer to the start of myVector’s data. I’m using a third party library where I must cache this pointer up front for use in a call made during the “process data…” section.
void setupBuffer(const size_t maxSize) {
myVector.reserve(maxSize);
cachePtr(&(myVector[0])); // doesn't work, obviously
}
I don’t want to resize() the vector up front, as I want to use vector.size() to mean the number of elements added to the vector.
So, is there any way to obtain the pointer to the vector’s buffer after allocation (reserve()) but before it has any elements? I would imagine the buffer exists (and won’t move as long as I restrict the number of push_back’d values)….maybe this isn’t guaranteed?
The vector buffer will not be moved after a call to reserve unless you exceed the reserved capacity. Your problem is getting the pointer to the first element. The obvious answer is to push a single fake entry into the vector, get the pointer to it, and then remove it.
A nicer approach would be if the library accepted a functor rather than a pointer, which it would call when it needed to access the buffer – you could make the functor put off getting the address until the buffer had some real contents. However, I realise you don’t have the luxury of rewriting the library.