c++ - How to treat a std::vector like a C buffer efficiently? -
with c buffer, 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 possible std::vector without losing performance?
edit: have found way replace raw c buffer std::vector.
std::vector<byte> vbuf; vbuf.reserve(max_size); // allocated @ once while (apprunning()) { int pendingsize = getpendingdatasize(); // socket 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); };
actually, in practical usage, receiving data , processing data may done in multithread. using vector, not need manage buffer's allocation, data size , buffer capacity manually. compares c buffer, performance penalty here @ vbuf.resize() calls. think penalty insignificant. better way appreciated.
if want behavior similar c (that is, want guarantee vector won't ever free or allocate more memory underlying vector), nice solution use boost's static_vector. statically allocates underlying buffer otherwise acts normal vector.
boost::static_vector<byte, max_size> buffer;
for type of activity, however, might std::queue or boost::cirular_buffer , see if 1 of fits needs.
Comments
Post a Comment