Question

The basic_streambuf member to set the three "gptrs" of the streambuf, setg, is declared as:

protected:
  void setg(char_type *gback, char_type *gptr, char_type *egptr);

I am wondering: why was the type of each gptr made char_type* instead of const char_type*? Is it safe to use const_cast here to use const char pointers for these gptrs?

Was it helpful?

Solution

It's not const because the streambuf interface doesn't know how you're populating the buffer. For example the underflow and uflow methods may pull n bytes from a file or similar and populate the extant buffer of the streambuf. You may also be using the same storage for the buffers for a read/write stream stream. The streambuf is a buffer, a cache if you will. It sits between the formatting functionality of the [io]stream and the actual underlying character stream (usually a file). It's a window on to that underlying stream, and it makes sense to reuse the storage for that window (which means it's probably not const).

Is it safe to cast away the const-ness? Maybe. It will depend on the actual streambuf implementation and how it is used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top