DrBob wrote:
I need to dynamically grow a buffer by concatinating raw binary data
in chunks.
How do I use 'new' to grow the buffer size as its contents grow? I
know this can be done with realloc.. (realloc will give you a new
pointer to a new buffer that has the same contents as the previous
buffer and will free the previous buffer for you).
realloc is basically a sequence of malloc new buffer, memcpy, free old
buffer. So you can just as easily do that yourself with new: create new
buffer, memcpy, delete old buffer.
Note that this has the danger of becoming a real performancekiller as your
buffer grows, since more and more data will need to be copied everytime you
grow. The best way to avoid too much copying if you must do this is probably
to double your buffer everytime, instead of just adding a single chunk size.
Perhaps there is a different class I could be using?
std::vector<unsigned char> will do all of the above for you with no
additional effort. It will double the buffer whenever it runs out of space.
A better approach might be keeping all the separate buffers in a
std::list<unsigned char*> or std::list<std::vector<unsigned char> >, then
when you have them all simply create a single buffer that's large enough for
all buffers and copy all the individual buffers into it. This minimizes
resizing and copying. It depends on what you're trying to do though.
--
Unforgiven
"You can't rightfully be a scientist if you mind people thinking
you're a fool."