Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

construct a vector in range without copying

I have a class that wraps a big array of bytes that are network packets. The class implements a queue and provides (among others) front() function that returns a const vector of bytes that constitute 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...
  [...]
}

The performance of above implementation of front() function suffers from unnecessary copying bytes from the range occupied by the current packet. Since the vector is const, there is no need of making a copy of the data. What I want is to create a vector on the data that are already stored in the buffer. Of course destructor of the vector should not deallocate the memory.

like image 439
Patryk Avatar asked Oct 31 '22 05:10

Patryk


1 Answers

You have some options available to you:

  1. Rather than returning a vector, just return a const char*:
const char* front() {
    return data;
}
  1. Consider using a standard container, such as a string data as your Buffer member. This will allow you to do:
const string& front() {
    return data;
}
  1. The best option though is if you have C++17 or access to experimental::string_view you could just do:
const string_view front() {
    return string_view(data);
}

Just a convention comment, there is going to be an expectation of front that it will behave like other standard containers, which:

Returns a reference to the first element in the container.
Calling front on an empty container is undefined.

[source]

Bringing front to apply to bare on fixed size arrays was also discussed by the C++ standards committee: front and back Proposal for iterators Library

As it is this method more closely resembles data, which:

Returns a pointer to the block of memory containing the elements of the container.

[source]

like image 96
Jonathan Mee Avatar answered Nov 15 '22 12:11

Jonathan Mee