With unopened I mean:
ofstream outFile;
outFile << "Some开发者_StackOverflow中文版 text";
So I put text in an ofstream
without call the .open()
method. g++ does not complain, so maybe I still can save the data? How?
The stream will be in a failure state after you do this (outFile.fail()
will be true). The text isn't stored anywhere, so no, you can't save it.
If you want to store data in memory, use an std::ostringstream
(from the <sstream>
header) instead.
g++ doesn't complain since it is a compiler and doesn't run the code, but running it may cause something nasty.
In the same way, g++ wouldn't complain if you attempt to dereference a NULL
pointer.
When an action with a stream fails, the stream's stores the error internally as bits representing eof, fail and bad. The stream can also throw an exception if you set it to with ios::exceptions().
Part of the design of the iostream library seems to be that using a stream that's in an error state will silently discard output and/or produce no input, but not otherwise alert the user. The benefit of this is that you can perform multiple operations using the stream and then check it at the end, confident that if it failed somewhere in the middle it's still in a failed state and didn't produce anything since it failed.
精彩评论