0

Consider a tempalted class InputBuffer:

template<class Source, size_t Capacity>
class InputBuffer
{
    public:
        explicit InputBuffer(Source src);

        int getchar();

    private:
        std::byte const* m_read_ptr;
        std::byte const* m_last_valid;
        Source m_src;
        std::array<std::byte, Capacity> m_data;

        void fetchAndResetPointers();
};

Question: Should the constructor instead accept src as a reference and store a pointer instead of taking it by value? It is very likely that the caller expect reference semantics here. However, it is also possible that Source already is some kind of pointer, and then, taking src by reference and storing a pointer would lead to an unnecessary indirection. If not passing by reference, the user can use std::ref if needed.

user877329
  • 6,717
  • 8
  • 46
  • 88

1 Answers1

-1

This class is no good as is in my opinion - you assume that "source" requires an m_read_ptr, m_last_valid and m_data as context. However, if it's a file, for instance, it requires non of these. Instead, rewrite this class as an interface, or better yet, don't create a generic class at all and use templates when handling "sources", example in pseudo-code:

class FileBuffer {
public:
  explicit FileBuffer(File* f) : m_f(f) {}
  int getchar() { return read(f, 1); }
private:
  File* m_f;
};

template<class T>
void print_from_buffer_to_stdout(T& buf) {
  std:: cout << buf.getchar();
}

int main() {
  FileBuffer f = get_file_buffer(); // somehow
  print_from_buffer_to_stdout(f);
}
NadavS
  • 779
  • 3
  • 12
  • In fact, `m_read_ptr` will point into the local buffer array, and `fetchAndResetPointers` will be called when the `buffer` is empty (`m_read_ptr == m_last_valid`). Your suggestion is not a buffer: It relies on `File` providing the buffer internally. The reason for using an InputBuffer, is that it could be a large overhead to call `read`, so you typically call read to fetch more than one byte, such as one entire page. – user877329 Apr 02 '20 at 20:22
  • you missed the point - The "inputbuffer" class should either not contain a "Source" as its member or not contain all the other members/methods. – NadavS Apr 03 '20 at 20:07
  • Sorry, but you do need read about how to implement buffered I/O. The implementation of the input buffer need to at least know its source, if it is not an argument to getchar. But it cannot be an argument to getchar, because that would introduces inconsistency. – user877329 Apr 04 '20 at 07:00