Are there consequences to writing to an unopened stream?

放肆的年华 提交于 2020-01-07 06:14:09

问题


If I have this:

std::ofstream empty;

for(int i = 0; i < 99999; ++i)
{
   empty << "Nothing..." << std::endl;
}

Will this ever cause an out of memory exception or any other problems since the stream is getting data pushed in but it is not going anywhere?

Thanks


回答1:


When the file stream is default-constructed, the 6 pointers to the internal buffer are initialized to nullptr. Any I/O attempted on the stream will fail because there is no available memory, and ios_base::badbit and ios_base::failbit will be set in the stream state.

Will this ever cause an out of memory exception or any other problems since the stream is getting data pushed in but it is not going anywhere?

The stream is allowed to throw std::bad_alloc in this case.




回答2:


You got it wrong. No data is "getting pushed" anywhere. If the stream is not opened, all output operations on it will fail, as you can easily tell yourself:

assert(!(empty << "foo"));



回答3:


If the stream is not open, it should be treated as NULL. So, the data being sent to the stream should be lost.



来源:https://stackoverflow.com/questions/20693758/are-there-consequences-to-writing-to-an-unopened-stream

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