c++ - nullptr 是假的吗?

标签 c++ c++11 language-lawyer implicit-conversion nullptr

当用作 bool 表达式或显式或隐式转换为 bool 值时,nullptr 是否始终为假?标准中是否定义或指定了此实现?

我写了一些代码来测试,但不确定它是否完全测试了这个属性。我找不到专门讨论此问题的现有 SO 答案。 cppreference从我所看到的没有提到这一点。

if (nullptr) {
    ;
} else {
    std::cout << "Evaluates to false implicitly\n";
}

if (!nullptr) {
    std::cout << "Evaluates to false if operated on\n";
}

if (!(bool)(nullptr)) {
    std::cout << "Evaluates to false if explicitly cast to bool\n";
}

预期和实际:

Evaluates to false implicitly
Evaluates to false if operated on
Evaluates to false if explicitly cast to bool

最佳答案

根据 C++ 17 标准(5.13.7 指针文字)

1 The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t. [ Note: std::nullptr_t is a distinct type that is neither a pointer type nor a pointer-to-member type; rather, a prvalue of this type is a null pointer constant and can be converted to a null pointer value or null member pointer value. See 7.11 and 7.12. — end note ]

和(7 次标准转换)

4 Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (11.6).

最后(7.14 bool 转换)

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer-to-member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (11.6), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

那是你可以写的例子

bool b( nullptr );

但你可能不会写(尽管一些编译器有一个与此相关的错误)

bool b = nullptr;

所以 nullptr 可以在上下文中转换为 bool 类型的对象,例如在 if 语句等选择语句中。

让我们以 if 语句中的一元运算符 ! 为例

if ( !nullptr ) { /*...*/ }

根据运算符的描述(8.5.2.1 一元运算符)

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

所以 nullptr 在这个表达式中没有被转换为指针。它直接根据上下文转换为 bool 值。

关于c++ - nullptr 是假的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57527189/

相关文章:

c++ - 如何选择为每个平台编译哪些源文件?

c++ - 禁止/重定向 C++ 删除?

c++11 - std::move-如何警告程序员不要使用* move 自*对象

c++ - GCC 拒绝使用 enum-base 的简单声明; clang 接受它——这是正确的吗?

c++ - 如何设置 QWidget 宽度?

c++ - 获取指向 lambda 的函数指针?

c++ - std::shared_ptr: reset() 与赋值

c++ - 在嵌套 lambda 的情况下如何初始化 lambda 捕获?

c++ - 比较从字符串转换的浮点值与文字

c++ - XCode 4 搜索中的相对#include 路径?