为什么 C++ 中布尔和指针有这种奇怪的兼容性?
这不仅有效并且即使使用 -Wall: 也不会发出任何警告,
void* p = false; // actually 'true' doesn't work here
bool b = "Hello, Boolean!";
而且此兼容性规则允许为错误类型选择重载函数/运算符。假设您为所有基本类型重载了运算符 <<
,并且忘记重载 void 指针,那么编译器可能会选择采用 bool
的版本,或者反过来说。
那么,是什么让这个兼容性规则比重载函数带来的奇怪(而且非常不受欢迎的)副作用更重要呢?
(编辑:删除了所有对 C 的引用,它们是错误的:转换规则在 C 中基本相同。)
Not only is this valid and doesn't give any warnings even with -Wall:
void* p = false; // actually 'true' doesn't work here
bool b = "Hello, Boolean!";
but also this compatibility rule permits selecting an overloaded function/operator for a wrong type. Let's say you overloaded your operator <<
for all fundamental types and you forgot to overload the void pointer, then the compiler may select the version that takes bool
, or the other way around.
So what is it that makes this compatibility rule more important than the weird (and highly undesirable) side effects with overloaded functions?
(Edit: removed all references to C, they were wrong: the conversion rules are basically the same in C.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“C 可以正确处理这个问题”是什么意思? C 不允许函数重载,因此保证您拥有 bool <->您抱怨的指针转换。
您想问为什么存在这种转换吗?
第一个实际上不是转换布尔值 ->指针,但识别文字
false
表示 0,这是一个有效的指针值。这就是为什么它不能与true
一起使用,也不能与bool
变量一起使用。第二个是因为能够编写:
而不是
检查指针是否包含空指针值是很好的。
编辑:影响
T* p = false;
的标准规则:并且
和
What do you mean by "C can handle this correctly"? C doesn't permit function overloading, so you are guaranteed to have the bool <-> pointer conversion you're complaining about.
Are you asking why this conversion exists?
The first is not actually a conversion bool -> pointer, but is recognizing that the literal
false
means 0, which is a valid pointer value. That's why it doesn't work withtrue
, and it doesn't work with abool
variable.The second is because it's nice to be able to write:
instead of
to check if a pointer holds a null pointer value.
EDIT: Rules from the standard influencing
T* p = false;
:and
and