Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would std::ostringstream convert to bool?

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?

like image 892
Drew Dormann Avatar asked Dec 06 '22 06:12

Drew Dormann


1 Answers

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.

like image 110
Naaff Avatar answered Dec 07 '22 19:12

Naaff