views:

622

answers:

3

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?

+8  A: 

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 the void* cast operator.

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.

Naaff
Actually this is achieved by overloading the void* cast operator. IF the bool cast operator was used then the stream could be used in an arithmetic context and the compiler would cast to bool and use the value 0/1. a void* on the other hand can not be used in an arithmetic context but can be used in a bool context as NULL pointers evaluated to false. But in this case the operator ! is used to explicitly return a bool value.
Martin York
Good point. That's what I get for going from memory. ;)
Naaff
What would that signify specifically for an ostringstream? Out of memory, perhaps?
Shmoopty
@Shmoopty: Same as for other streams. Attempt to read an integer from characters will set some error bit. Check out http://www.cplusplus.com/reference/iostream/ios/fail/
Martin York
@Martin York: I see how that could happen with an istream. How can an ostringstream attempt to read an integer from characters as you describe?
Shmoopty
@Shmoopty: I'm not sure how and ostringstream could fail. Running out of memory might do it, but I'm willing to bet that full memory just results in an exception rather than setting fail. What is clear is that ostringstream inherits from ios_base just like any std stream class, so it inherits the state flags as well, even if there is not as much call for them as there is in a class like ofstream or istringstream.
Naaff
+1  A: 

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.

anon
+2  A: 

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

Donotalo