0

I have a class that represents a buffer in memory

class Buffer
{
public:
    Buffer(const char* buffer, size_t size)
        :m_buffer(buffer), m_size(size)
    {
    }

    const char* m_buffer;
    size_t m_size;
};

I need to overload operator<< on this class so that it can be written to a std::stringstream like this

char arr[] = "hello world";
Buffer buf(arr, 11);
std::stringstream ss;
ss << buf;

How do I do this? Note that the memory buffer might have NULL chars in between. Also, since the memory buffer can be large, I want to avoid making any extra copies of this (other than the copy into the stringstream).

0

2 Answers 2

5

Writing to a stream is always done to an output stream.

If you see e.g. this std::stringstream reference you will see that it inherits from std::iostream which inherits from std::ostream (as well as from std::istream).

That means you simply overload it like this:

class Buffer
{
public:
    ...

    friend std::ostream& operator<<(std::ostream& os, Buffer const& buf)
    {
        // Code to write the buffer to the stream...
    }
};

This overload of course means you can use the Buffer class to write to any output stream.

Exactly what's needed in the overloaded function to write the data depends on the data. Can it be any generic binary data then you should probably use std::ostream::write. Otherwise you could just use e.g. std::string to act as an intermediate:

return os << std::string(m_buffer, m_size);

You of course need to make sure that the buffer is not empty, or a null pointer.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please help me with what should go into this function (code to write the buffer to the stream)? Thanks.
I would like to avoid making extra copies of the buffer (into an intermediate std::string)
Inside the friend function's definition: return os.write(buf.m_buffer, buf.m_size); A caveat exists because write takes a signed integer size parameter (type std::streamsize), whose bit count typically matches or exceeds size_t, so if you want to ensure support for very large buffers, you will have to check the maximum std::streamsize value, and if m_size is greater, break up the write operation into multiple chunks.
2

Use std::ostream::write() in your operator<< overload to write the buffer to the std::ostream.

This will write everything, null bytes, et al.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.