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

后端 未结 3 558
我寻月下人不归
我寻月下人不归 2021-02-03 22:59

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

3条回答
  •  佛祖请我去吃肉
    2021-02-03 23:02

    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.

提交回复
热议问题