Build a vector in a range without copying

I have a class that wraps a large array of bytes that are network packets. The class implements the queue and provides (among other things) a function front()that returns the const vector from the bytes that make up the oldest packet in the queue.

class Buffer{
  unsigned char data[65536];
  unsigned int offset;
  unsigned int length;
  [...]//other fields for maintaining write ptr etc.

public:
  const std::vector<unsigned char> front(){
    return std::vector<unsigned char>(data + offset, data + offset + length);
  }

  //other methods for accessing the queue like
  //pop(), push(), clean() and so forth...
  [...]
}

Performance above function implementations front()suffers from unnecessary copies of bytes from the range occupied by the current packet. Since the vector is const, there is no need to make a copy of the data. I want to create a vector on data that is already stored in a buffer. Of course, the vector destructor should not free memory.

+4
2

:

  • vector const char*:
const char* front() {
    return data;
}
  1. , string data Buffer. :
const string& front() {
    return data;
}
  1. , ++ 17 experimental::string_view, :
const string_view front() {
    return string_view(data);
}

, , front , :

.
undefined.

[]

++: front and back

data, :

, .

[]

+1

, . front_begin() front_end():

const char *front_begin() const
{
  return data + offset;
}

const char *front_end() const
{
  return data + offset + length;
}

:

class Data
{
private:
  const char *m_Begin;
  const char *m_End;

public:
  Data(const char *begin, const char *end) : m_Begin(begin), m_End(end)
  {
  }

  const char *begin() const
  {
    return m_Begin;
  }

  const char *end() const
  {
    return m_End;
  }
}

front() :

Data front()
{
  return Data(data + offset, data + offset + length)
}

++ 11, Data , :

Data data = buffer.front();
for(char c : data)
{
  // Do something with the data
}
0

All Articles