要实现 MT 安全,必须在具有可能导致出现错误的 I/O 操作的关键区中进行错误检查。以下示例说明了如何检查错误:
#include <iostream.h>
enum iostate {IOok, IOeof, IOfail};
iostate read_number(istream& istr, int& num)
{
stream_locker sl(istr, stream_locker::lock_now);
istr >> num;
if (istr.eof()) return IOeof;
if (istr.fail()) return IOfail;
return IOok;
}
|
在此示例中,stream_locker 对象 sl 的构造函数锁定 istream 对象 istr。在 read_number 终止时调用的析构函数 sl 解锁 istr。