When should I concern myself with std::iostream::sentry?

こ雲淡風輕ζ 提交于 2019-11-29 01:45:46

问题


Online references have rather brief and vague descriptions on the purpose of std::iostream::sentry. When should I concern myself with this little critter? If it's only intended to be used internally, why make it public?


回答1:


Most people will never write any code that needs to deal with creating sentry objects. A sentry object is needed when/if you extract data from (or insert it into) the stream buffer that underlies the stream object itself.

As long as your insertion/extraction operator uses other iostream members/operators to do its work, it does not have to deal with creating a sentry object (because those other iostream operators will create and destroy sentry objects as needed).




回答2:


It's used whenever you need to extract or output data with a stream. That is, whenever you make an operator>>, the extraction operator, or operator<<, the insertion operator.

It's purpose is to simplify the logic: "Are any fail bits set? Synchronize the buffers. For input streams, optionally get any whitespace out of the way. Okay, ready?"

All extraction stream operators should begin with:

// second parameter to true to not skip whitespace, for input that uses it
const std::istream::sentry ok(stream, icareaboutwhitespace);

if (ok)
{
    // ...
}

And all insertion stream operators should begin with:

const std::ostream::sentry ok(stream); 

if (ok)
{
    // ...
}

It's just a cleaner way of doing (something similar to):

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 just skips the whitespace part.




回答3:


Formatted input for anything but the basic types (int, double, etc.) doesn't make a lot of sense, and arguably only from them when taken from a non-interactive stream such as an istringstream. So you should probably not be implementing op>> in the first place, and thus not have to worry about sentry objects.



来源:https://stackoverflow.com/questions/2298604/when-should-i-concern-myself-with-stdiostreamsentry

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