I am working on some code which is a state machine, and different classes are responsible for different kind of task, all of which are acquiring data. Upon completing the data acquisition, the data needs to be sent away. The class responsible looks something like this:
class SendBuffer {
std::uint8_t* get_position(/*some arguments to determine buffer*/) {
return &buffer[/*at determined location*/];
}
private:
std::array<std::uint8_t, MAX_SIZE> buffer;
};
Of course, this is not safe at all, because the returned pointer has no information of how long the dedicated slice in the buffer is, etc.
I considered returning std::span<std::uint8_t> instead of a raw pointer, but I was wondering what the best practices are here.
Using
std::span(cppreference) is the way to go. It can be initialized from views, as mentioned in the comments. Alternativelyspan's member functions provide useful utilities. In case of the question, a single value can be returned as a span using thesubspan(offset, extent)function.For a single value returning a reference might be more useful though. But for subranges of the buffer,
span'ssubspan,firstandlastare convenient. Some examples:Note that
subspan,firstandlasthave static and dynamic overloadsWhere upper case letters denote compile time constants and lower case letters can also be run time sizes.