为什么 C++ 中布尔和指针有这种奇怪的兼容性?

发布于 2024-10-01 01:43:01 字数 377 浏览 6 评论 0原文

这不仅有效并且即使使用 -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 技术交流群。

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

发布评论

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

评论(1

囚你心 2024-10-08 01:43:01

“C 可以正确处理这个问题”是什么意思? C 不允许函数重载,因此保证您拥有 bool <->您抱怨的指针转换。

您想问为什么存在这种转换吗?

第一个实际上不是转换布尔值 ->指针,但识别文字 false 表示 0,这是一个有效的指针值。这就是为什么它不能与 true 一起使用,也不能与 bool 变量一起使用。

第二个是因为能够编写:

if (p)

而不是

if (p != 0)

检查指针是否包含空指针值是很好的。

编辑:影响 T* p = false; 的标准规则:

空指针常量是整数类型的整型常量表达式纯右值,其计算结果为零

并且

类型 bool、char、char16_t、char32_t、wchar_t 以及有符号和无符号整数类型统称为整型。整数类型的同义词是整型。

布尔文字是关键字 false 和 true。这些文字是纯右值并且具有 bool 类型。

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 with true, and it doesn't work with a bool variable.

The second is because it's nice to be able to write:

if (p)

instead of

if (p != 0)

to check if a pointer holds a null pointer value.

EDIT: Rules from the standard influencing T* p = false;:

A null pointer constant is an integral constant expression prvalue of integer type that evaluates to zero

and

Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type.

and

The Boolean literals are the keywords false and true. Such literals are prvalues and have type bool.

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