我们正在捕获一个Coverity查找 CID 156014:未还原ostream格式(STREAM_FORMAT_STATE)(下面的文本和结尾的图像)。
938 const std::streamsize oldp = cout.precision(6);
5. format_changed: setf changes the format state of std::cout for category floatfield.
939 const std::ios::fmtflags oldf = cout.setf(std::ios::fixed, std::ios::floatfield);
940 cout << " Maurer Randomness Test returned value " << mv << endl;
6. format_changed: precision changes the format state of std::cout for category precision.
941 cout.precision(oldp);
7. format_restored: setf changes the format state of std::cout for category floatfield.
942 cout.setf(oldf, std::ios::floatfield);
出现在第941行,
cout.precision(oldp)
是一个问题。 Coverity似乎将其分类为更改,而不是还原。根据set back default precision C++关于SO的说法,我相信我们正在做建议的事情。 (但是我可能是错的,或者被接受的答案可能不是最佳实践)。
我们如何恢复精度并压缩Coverity发现?
我最近对以下内容感到厌倦,但它继续产生发现
format_changed: setf changes the format state of std::cout for category floatfield
。// Coverity finding
class StreamState
{
public:
StreamState(std::ostream& out)
: m_out(out), m_fmt(out.flags()), m_prec(out.precision())
{
}
~StreamState()
{
m_out.precision(m_prec);
m_out.flags(m_fmt);
}
private:
std::ostream& m_out;
std::ios_base::fmtflags m_fmt;
std::streamsize m_prec;
};
...
StreamState ss(cout);
cout.setf(std::ios::fixed, std::ios::floatfield);
cout.precision(6);
cout << " Maurer Randomness Test returned value " << mv << endl;
最佳答案
经过大约6次尝试(我认为我们已经使用了一周的所有提交内容),看来无法使用成员函数在程序中设置floatfield
(即 ostream.iosflags(...); ostream.precision(...)
)。我们必须将操纵器用于floatfield
(即 ostream << setiosflags(...) << setprecision(...)
):
// Coverity finding
class StreamState
{
public:
StreamState(std::ostream& out)
: m_out(out), m_fmt(out.flags()), m_prec(out.precision())
{
}
~StreamState()
{
m_out.precision(m_prec);
m_out.flags(m_fmt);
}
private:
std::ostream& m_out;
std::ios_base::fmtflags m_fmt;
std::streamsize m_prec;
};
和:
StreamState ss(cout);
cout << std::setiosflags(std::ios::fixed) << std::setprecision(6);
cout << " Maurer Randomness Test returned value " << mv << endl;
关于c++ - 查找覆盖范围:不还原ostream格式(STREAM_FORMAT_STATE),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34503914/