[英]Do I have to lock to check a work-available flag used with a condition variable before setting it, and if so why?
[英]Why do I have to set the error state flag to goodbit in order for this to work?
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ofstream os("test.txt");
std::ifstream is("test.txt");
std::string value("0");
os << "Hello";
is >> value;
std::cout << "Result before tie(): \"" << value << "\"\n";
is.clear();
is.tie(&os);
is >> value;
std::cout << "Result after tie(): \"" << value << "\"\n";
}
上面的代码具有输出:
Result before tie(): "0"
Result after tie(): "Hello"
但是如果没有clear()
调用, value
保持为“ 0”-为什么? 为什么必须将输入流的错误状态标志设置为goodbit?
请注意,找不到文件,这是有意的。
可能发生的是,当您从is
读取value
时,您命中了文件结尾。 显然,不会通过tie()
清除输出流来清除该标志。
如果EOF标志保持设置状态,则不会从流中读取其他字符,因此尝试读取value的新value
将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.