What could cause a stream to enter the “bad” state?

谁说胖子不能爱 提交于 2019-12-12 07:27:10

问题


In C++, each stream has a bad bit:

This flag is set by operations performed on the stream when an error occurs while read or writing data, generally causing the loss of integrity of the stream.

Source

What would cause a stream to "lose integrity" and enter the bad state? This is not the same as the fail state, which most often occurs when an input stream attempts to store a value into a variable that cannot accept said value (such as attempting to store a string into an integer variable).

Note that this question is a more general form of c++ file bad bit, which is specific to file input streams; this question is not an exact duplicate as it applies to both input and output streams in general.


回答1:


According to cppreference.com :

The standard library sets badbit in the following situations:

  • Insertion into the output stream by put() or write() fails for any reason.

  • Insertion into the output stream by operator<<, std::put_money or std::put_time, could not complete because the end of the output stream was reached (The facet's formatting output function such as num_put::put() or money_put::put(), returns an iterator iter such that iter.failed()==true)

  • Stream is constructed with a null pointer for rdbuf(), or putback()/unget() is called on a stream with a null rdbuf(), or a null pointer passed to operator<<(basic_streambuf*)

  • rdbuf()->sputbackc() or rdbuf()->sungetc() return traits::eof() to putback() orunget()`

  • rdbuf()->pubsync() returns -1 to sync(), to flush(), or to the destructor of ostream::sentry on a unitbuf stream

  • Exception is thrown during an I/O operation by any member function of the associated stream buffer (e.g. sbumpc(), xsputn(), sgetc(), overflow(), etc)

  • Exception is thrown in iword() or pword() (e.g. std::bad_alloc)


This may be one more reason to choose cppreference.com over www.cpluplus.com, see: What's wrong with cplusplus.com?




回答2:


Take a look at the Apache C++ Standard Library User's Guide. Two potential causes for a badbit are listed there. I quote:

Memory shortage: There is no memory available to create the buffer, or the buffer has size 0 for other reasons (such as being provided from outside the stream), or the stream cannot allocate memory for its own internal data.

The underlying stream buffer throws an exception: The stream buffer might lose its integrity, as in memory shortage, or code conversion failure, or an unrecoverable read error from the external device. The stream buffer can indicate this loss of integrity by throwing an exception, which is caught by the stream and results in setting the badbit in the stream's state.



来源:https://stackoverflow.com/questions/12161728/what-could-cause-a-stream-to-enter-the-bad-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!