Horstmann’s C++ pitfalls在谈论流时解决了一个有趣的问题。引用他的话:
Use conversion to
void*
, not conversion toint
orbool
, to implement objects yielding truth values. Unlikeint
orbool
,void*
have no legal operations other than==
comparison.
作为一名程序员,如果某些函数在我期望 boolean 值时返回 void*
,我会感到困惑。 Horstmann 提供了一个示例,其中使用 void*
而不是 bool
似乎是合适的。它总是可取的吗?
最佳答案
一般情况下不建议这样做,对于 C++11,根本不建议这样做。
转换为 void*
的原因是支持像这样的语法
std::ifstream myStream;
if (myStream) {
}
if (!myStream) {
}
在这里,转换为 bool
似乎更合理,但会导致像这样的怪异现象:
if (myStream == true) // ??
转换为 void*
会阻止此代码合法化,但会引发其他问题,例如
delete myStream; // ??
在 C++11 中,由于能够将 explicit operator bool()
作为成员函数,因此此 void*
hack 已被弃用,不应使用。不要使用这个成语。如果您需要某些东西来返回 bool
,请让它返回 bool
。如果您需要一个可以转换为 bool
的对象,请使用 explicit operator bool
。
希望这对您有所帮助!
关于c++ - 使用 void* 而不是 bool 是一种可取的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9134888/