ruipacheco ruipacheco - 1 month ago 7
C++ Question

Why is my overloaded << not returning any data?

I have a class that loads a

vector<unsigned char>
using Asio's asynchronous methods. I then overloaded the << operator to return that data.

The problem is that even though the buffer is full and valid, the operator does not return any data.

My buffer:
vector<unsigned char>read_buffer;


Operator declaration:

friend std::vector<unsigned char> operator<<(const vector<unsigned char>output, const shared_ptr<Socket>socket) noexcept;


The implementation:

std::vector<unsigned char> operator<<(const vector<unsigned char>output,
const shared_ptr<Socket>socket) noexcept {
std::cerr << output.size() << std::endl;
std::cerr << socket->read_buffer.size() << std::endl;
return socket->read_buffer;
}


where
std::cerr << socket->read_buffer.size() << std::endl;
has the right size and step by step debugging show its content is also valid.

But when I get data back:

vector<unsigned char> response;
response << socket;


response
is empty. I've tried initialising it to the length of the expected response but I just end up with a buffer with X null characters.

Stumped by this. Shouldn't a return statement copy or move the value out?

Answer
response << socket;

means

operator<<(response, socket);

and in this form it's clear that you're discarding the return value.

That the code compiles with a prototype that reads const vector<unsigned char>output is another hint that you're never modifying the output vector.

If you want this to work like the stream insertion operators - appending to the left-hand side and being chainable, like so:

 response << socket << another_socket;

the first parameter should be a non-const reference, and you should return a non-const reference to the same object:

vector<unsigned char>& operator<<(vector<unsigned char>& output,
                                  const shared_ptr<Socket>socket) noexcept 
{
      output.insert(output.end(), socket->read_buffer.begin(), socket->read_buffer.end());
      return output;
}
Comments