gpt4 book ai didi

c++ - 当空指针不是所有位为零时如何正确编写 C/C++ 代码

转载 作者:IT老高 更新时间:2023-10-28 12:09:47 25 4
gpt4 key购买 nike

作为 comp.lang.c FAQ说,有些架构中的空指针并非全为零。所以问题是实际检查以下构造:

void* p = get_some_pointer();
if (!p)
return;

我是将 p 与机器相关的空指针进行比较,还是将 p 与算术零进行比较?

我应该写吗

void* p = get_some_pointer();
if (NULL == p)
return;

而不是为这样的架构做好准备,还是只是我的偏执狂?

最佳答案

根据 C 规范:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. 55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

所以 0 是一个空指针常量。如果我们将它转​​换为指针类型,我们将得到一个空指针,对于某些体系结构,它可能是非全位为零的。接下来让我们看看规范中关于比较指针和空指针常量的内容:

If one operand is a pointer and the other is a null pointer constant, the null pointer constant is converted to the type of the pointer.

让我们考虑(p == 0):首先将0转换为空指针,然后将p与空指针进行比较指针常量,其实际位值取决于架构。

接下来,看看规范中关于否定运算符的内容:

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

这意味着 (!p) 等价于 (p == 0),根据规范,测试 p针对机器定义的空指针常量。

因此,即使在空指针常量并非全为零的架构上,您也可以安全地编写 if (!p)

对于C++,空指针常量定义为:

A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.

这与我们为 C 所拥有的很接近,加上 nullptr 语法糖。运算符 == 的行为由以下定义:

In addition, pointers to members can be compared, or a pointer to member and a null pointer constant. Pointer to member conversions (4.11) and qualification conversions (4.4) are performed to bring them to a common type. If one operand is a null pointer constant, the common type is the type of the other operand. Otherwise, the common type is a pointer to member type similar (4.4) to the type of one of the operands, with a cv-qualification signature (4.4) that is the union of the cv-qualification signatures of the operand types. [ Note: this implies that any pointer to member can be compared to a null pointer constant. — end note ]

这导致 0 转换为指针类型(与 C 一样)。对于否定运算符:

The operand of the logical negation operator ! is contextually converted to bool (Clause 4); its value is true if the converted operand is true and false otherwise. The type of the result is bool.

这意味着 !p 的结果取决于如何执行从指针到 bool 的转换。标准说:

A zero value, null pointer value, or null member pointer value is converted to false;

所以 if (p==NULL)if (!p) 在 C++ 中也做同样的事情。

关于c++ - 当空指针不是所有位为零时如何正确编写 C/C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32136092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com