std::vector<char> or std::ostringstream

C

Chris

Hi,

I'm playing/developing a simple p2p file sharing client for an existing
protocol.

A 2 second description of the protocol is

Message Length = int, 4 bytes
Message Code = int, 4 bytes
Data

When creating messages is easy to use a std::eek:stringstream and when
reading received messages, it easy to use a std::vector<char>.

I unclear as to which is more appropriate/efficient for the task and
was hoping some light could be shared on this, i have asked on irc
and been told 'it depends'. What does it depend on? :)

Thanks.
Chris
 
J

John Harrison

Chris said:
Hi,

I'm playing/developing a simple p2p file sharing client for an existing
protocol.

A 2 second description of the protocol is

Message Length = int, 4 bytes
Message Code = int, 4 bytes
Data

When creating messages is easy to use a std::eek:stringstream and when
reading received messages, it easy to use a std::vector<char>.

I unclear as to which is more appropriate/efficient for the task and
was hoping some light could be shared on this, i have asked on irc
and been told 'it depends'. What does it depend on? :)

Thanks.
Chris

Well the most important point is that you create a Message class and that
whatever representation you choose is internal to that. Apart from anything
else it will isolate any changes to the representation from the rest of the
program.

The advantage of ostringstream is that its give you nice formatting, the
advantage of vector<char> is that you can resize to fit the message length.
Maybe the best answer would be a combination of the two. Write a
std::streambuf derived class which wraps a vector<char> held as a reference
(have a look at std::stringbuf, your code will be very similar). Now your
Message class can use a vector<char> directly for reading and wrap the same
vector<char> in your streambuf derived class for reading.

Or something like that.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top