问题描述
在中我讨论使用 std :: ifstream
对象转换为 bool
来测试流是否仍处于良好状态。我在Josuttis的书中查看了更多的信息(如果你感兴趣的话,第600页),事实证明 iostream
对象实际上重载 void *
。当流错误(可以隐式转换为 false
)时返回空指针,否则返回非空指针(隐式转换为 true
)。为什么他们只是重载 operator bool
?
In this answer I talk about using a std::ifstream
object's conversion to bool
to test whether the stream is still in a good state. I looked in the Josuttis book for more information (p. 600 if you're interested), and it turns out that the iostream
objects actually overload operator void*
. It returns a null pointer when the stream is bad (which can be implicitly converted to false
), and a non-null pointer otherwise (implicitly converted to true
). Why don't they just overload operator bool
?
推荐答案
一个安全bool问题的实例。
This is an instance of the "safe bool" problem.
这里是一篇好文章:。
C ++ 0x可帮助 explicit
转换函数,以及Kristo提到的更改。另请参见。
C++0x helps the situation with explicit
conversion functions, as well as the change that Kristo mentions. See also Is the safe-bool idiom obsolete? .
这篇关于为什么没有iostream对象重载operator bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!