使用 void* 而不是 bool 是明智的做法吗?
Horstmann 的 C++ 陷阱 在谈论流时解决了一个有趣的问题。引用他的话:
使用转换为
void*
,而不是转换为int
或bool
,来实现产生真值的对象。与int
或bool
不同,void*
除了==
比较之外没有合法操作。
作为一名程序员,如果某些函数在我期望布尔值时返回 void*
,我会感到困惑。 Horstmann 提供了一个示例,其中使用 void*
而不是 bool
似乎是合适的。这总是可取的吗?
Horstmann’s C++ pitfalls tackles an interesting point when talking about streams. To quote him:
Use conversion to
void*
, not conversion toint
orbool
, to implement objects yielding truth values. Unlikeint
orbool
,void*
have no legal operations other than==
comparison.
As a programmer, I would be puzzled if some function returned void*
when I expect a boolean. Horstmann provides an example where using a void*
instead of a bool
seems appropriate. Is it always advisable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般情况下不建议这样做,对于 C++11 则根本不建议这样做。
转换为
void*
的原因是为了支持这样的语法:这里,转换为
bool
似乎更合理,但会导致如下奇怪的情况:转换为
void*
阻止了这段代码的合法性,但是却带来了一大堆蠕虫,就像在 C++11 中一样,能够将
显式运算符 bool()
作为成员函数,这个void*
黑客是已弃用且不应使用。不要使用这个习语。如果您需要返回bool
,请让它返回bool
。如果您需要一个可以转换为bool
的对象,请使用显式运算符 bool
。希望这有帮助!
This is not advised in general circumstances and, with C++11, is not advised at all.
The reason for the conversion to
void*
was to support syntax likeHere, a conversion to
bool
seems more reasonable, but leads to weirdnesses like this:The conversion to
void*
prevents this code from being legal, but opens up a whole other can of worms, likeIn C++11, with the ability to have
explicit operator bool()
as a member function, thisvoid*
hack is deprecated and should not be used. Don't use this idiom. If you need something to return abool
, have it return abool
. If you need an object that can be converted to abool
, useexplicit operator bool
.Hope this helps!