网上参考资料对目的的描述相当简短和模糊std::iostream::sentry
。我什么时候应该关心这个小动物?如果只是为了内部使用,为什么要公开呢?
每当您需要使用流提取或输出数据时,都会使用它。也就是说,每当你创建一个operator>>
、提取运算符,或operator<<
,插入运算符。
其目的是简化逻辑:“是否设置了任何失败位?同步缓冲区。对于输入流,可以选择去掉任何空格。好吧,准备好了吗?”
所有提取流操作符应以以下内容开头:
// second parameter to true to not skip whitespace, for input that uses it
const std::istream::sentry ok(stream, icareaboutwhitespace);
if (ok)
{
// ...
}
所有插入流运算符都应以:
const std::ostream::sentry ok(stream);
if (ok)
{
// ...
}
这只是一种更干净的做法(类似于):
if (stream.good())
{
if (stream.tie())
stream.tie()->sync();
// the second parameter
if (!noskipwhitespace && stream.flags() & ios_base::skipws)
{
stream >> std::ws;
}
}
if (stream.good())
{
// ...
}
ostream
只是跳过空白部分。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)