5

I've a customized std::streambuf. Something like:

class mybuf : public std::streambuf {
  ...
  virtual std::streambuf::int_type underflow() {
    if(eof) {
     return traits_type::eof();
    }
    ...
  }
  ...
  std::istream stream(new mybuf(...));

Setting the eof flag of the stream is done by returning eof on the underflow() function.

How can I set the badbit flag of the stream? Should the overflow() function throw an exception?

powerpete
  • 2,663
  • 2
  • 23
  • 49
  • 1
    throw an exception, yes. See : https://stackoverflow.com/questions/12161728/what-could-cause-a-stream-to-enter-the-bad-state (or direct link to [`ios_base::iostate`](http://en.cppreference.com/w/cpp/io/ios_base/iostate)) – Sander De Dycker Jun 06 '18 at 09:30

1 Answers1

2

Throwing an exception is indeed the way to go.

Refer to the reference page for std::ios_base::iostate, and specifically this :

The badbit is set by the following standard library functions:

  • ...
  • Every stream I/O function if an exception is thrown by any member function of the associated stream buffer (e.g. sbumpc(), xsputn(), sgetc(), overflow(), etc)
  • ...
Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40