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.
You have some options available to you:
vector
, just return a const char*
:const char* front() {
return data;
}
string data
as your Buffer
member. This will allow you to do:const string& front() {
return data;
}
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With