How would std::ostringstream convert to bool?

陌路散爱 提交于 2019-12-31 02:35:11

问题


I stumbled across this code.

    std::ostringstream str;
    /// (some usage)
    assert( ! str );

What does ostringstream signify when used in a bool context?

Is this possibly an incorrect usage that happens to compile and run?


回答1:


It tells you if the stream is currently valid. This is something that all streams can do. A file stream, for example, can be invalid if the file was not opened properly.

As a side note, this functionality (testing a stream as a bool) is achieved by overloading explicit operator bool in C++11 and later and by overloading the void* cast operator in versions before C++11.

Here is a link containing some examples of why a stream might fail. This isn't specific to string streams, but it does apply to them.

Edit: changed bool to void* after Martin York pointed out my mistake.




回答2:


For reference: ostringstream::operator void*() and ostringstream::operator!().




回答3:


The expression is valid and evaluates the state of the stream. This feature is more commonly used on input streams:

istringstream is;
is.str( "foo" );
int x;
is >> x;

if ( ! is ) {
   cerr << "Conversion failed";
}

I'm not sure how any of the standard streaming functions could cause an ostringstream to go bad, but you could certainly write one yourself.



来源:https://stackoverflow.com/questions/835590/how-would-stdostringstream-convert-to-bool

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