简体   繁体   中英

Why is the “gptr” type of basic_streambuf char_type* rather than const char_type*?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM