为什么C++流使用状态位

Why C++ streams use state bits?

本文关键字:状态 C++ 为什么      更新时间:2023-10-16

我听说当需要更高的性能时会使用C++。C++流使用位的概念来处理意外输入、格式化等。我认为这对性能不好,因为程序必须在每次读写时进行比较。例如,在MSVC中,std::basic_ostream::operator<<(int)的某些部分实现如下:

if (_Bfl == ios_base::oct || _Bfl == ios_base::hex) {
_Tmp = static_cast<long>(static_cast<unsigned int>(_Val));
} else {
_Tmp = static_cast<long>(_Val);
}

我的问题是,编译器优化是否减少了这些计算?如果不是,为什么C++标准采用状态位的概念?这费用微不足道吗?

对于像cout << std::hex << 1234这样的格式,我们可以使用这样的格式类:

struct Format
{
std::ostream* optr;
Format&& operator<< (int i) && { ... }
Format&& operator<< (double d) && { ... }
...
template <typename T>
Format&& operator<<(const T& other) && {
(*optr) << other;
return std::move(*this);
}
};
Format&& operator<<(std::ostream& os, Format&& format)
{
format.optr = &os;
return std::move(format);
}
...
std::cout << Format() << 123 << ' ' << 456;

抛开你的想法,甚至stdlib本身的设计/实现都没有考虑到绝对的性能(但在许多情况下是或接近(。流媒体库尤其如此,因为它不是为关键性能而设计的。