使用 void* 而不是 bool 是明智的做法吗?

发布于 2025-01-02 06:59:37 字数 465 浏览 5 评论 0原文

Horstmann 的 C++ 陷阱 在谈论流时解决了一个有趣的问题。引用他的话:

使用转换为void*,而不是转换为intbool,来实现产生真值的对象。与 intbool 不同,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 to int or bool, to implement objects yielding truth values. Unlike int or bool, 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

極樂鬼 2025-01-09 06:59:37

一般情况下不建议这样做,对于 C++11 则根本不建议这样做。

转换为 void* 的原因是为了支持这样的语法

std::ifstream myStream;
if (myStream) {

}
if (!myStream) {

}

:这里,转换为 bool 似乎更合理,但会导致如下奇怪的情况:

if (myStream == true) // ??

转换为 void* 阻止了这段代码的合法性,但是却带来了一大堆蠕虫,就像

delete myStream; // ??

在 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 like

std::ifstream myStream;
if (myStream) {

}
if (!myStream) {

}

Here, a conversion to bool seems more reasonable, but leads to weirdnesses like this:

if (myStream == true) // ??

The conversion to void* prevents this code from being legal, but opens up a whole other can of worms, like

delete myStream; // ??

In C++11, with the ability to have explicit operator bool() as a member function, this void* hack is deprecated and should not be used. Don't use this idiom. If you need something to return a bool, have it return a bool. If you need an object that can be converted to a bool, use explicit operator bool.

Hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文