With buffer C, I often do this:
BYTE buffer[MAX_SIZE];
int dataSize = 0;
while (appRunning())
{
dataSize += Receive(buffer + dataSize, MAX_SIZE - dataSize);
int processedSize = ProcessBuffer(buffer, dataSize);
ASSERT(processedSize <= dataSize);
dataSize -= processedSize;
memmove(buffer, buffer + processedSize, dataSize);
};
Is it possible to do this with std::vectorno loss in performance?
EDIT: I found a way to replace the raw C buffer with std::vector.
std::vector<BYTE> vbuf;
vbuf.reserve(MAX_SIZE);
while (appRunning())
{
int pendingSize = GetPendingDataSize();
if (pendingSize > vbuf.capacity())
pendingSize = vbuf.capacity();
vbuf.resize(pendingSize);
int recvSize = Receive(vbuf.data(), vbuf.size());
ASSERT(recvSize < vbuf.size());
int processedSize = ProcessBuffer(vbuf.data(), vbuf.size());
std::rotate(vbuf.begin(), vbuf.begin() + processedSize, vbuf.end());
vbuf.resize(vbuf.size() - processedSize);
};
In fact, in my practical use, data acquisition and data processing can be performed in multi-threaded mode. Thus, using vector, I don’t need to control the buffer allocation, data size and buffer capacity manually. Compared to buffer C, here vbuf.resize()performance occurs at vbuf.resize(). But I think the penalty is negligible. Any better way is appreciated.
source
share