Boost logo

Boost :

Subject: Re: [boost] Interest in a simple buffer abstraction?
From: Boris Kolpackov (boris_at_[hidden])
Date: 2011-01-27 07:37:20


Hi Mathias,

Mathias Gaunard <mathias.gaunard_at_[hidden]> writes:

> How is that any different from std::vector<char>?

Ah, that's right, I forgot to cover this case. The main problem with
using vector<char> as a binary buffer is the unnatural interface.

Provided:

typedef std::vector<char> vbuffer;

Compare:

       buffer vbuffer
--------------------------------------------------------------------
                             |
buffer b (data, size); | vbuffer b (data, data + size);
                             |
const char* p = b.data (); | const char* p = &b[0];
                             |
b.copy (data, size); | b.assign (data, data + size);
                             |
b.append (data, size); | b.insert (b.end (), data, data + size);

Also, you cannot pass the data to vector as void* which will be possible
with the buffer class, for example:

void* data;
...
buffer b (data, size); // Ok.
vbuffer vb (data, data + size); // Error.

Plus, some natural to have functions are not available in vector, for
example:

buffer b (size, capacity);
buffer b (data, size, capacity);

Also, for a binary buffer it is nice to be able to assume ownership of
an existing raw buffer and to detach the underlying raw buffer.

Finally, the implementation of std::vector<char> may not be as efficient
(e.g., using loops to copy elements instead of memcpy, etc).

So, to summarize, yes, it is possible to use vector as a binary buffer
(and a lot of people do so), but a separate buffer class will be able
to provide a more natural interface and also some additional
functionality.

Boris

-- 
Boris Kolpackov, Code Synthesis        http://codesynthesis.com/~boris/blog
Compiler-based ORM system for C++      http://codesynthesis.com/products/odb
Open-source XML data binding for C++   http://codesynthesis.com/products/xsd
XML data binding for embedded systems  http://codesynthesis.com/products/xsde

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk