我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?

2023-02-13C/C++开发问题
4

本文介绍了我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

通过简单地编写 if(pointer) 来检查指针是否为 NULL 是否安全,或者我是否必须使用 if(pointer != NULL)?

Is it safe to check a pointer to not being NULL by writing simply if(pointer) or do I have to use if(pointer != NULL)?

推荐答案

你可以;空指针被隐式转换为布尔值 false 而非空指针被转换为 true.来自 C++11 标准,关于布尔转换的部分:

You can; the null pointer is implicitly converted into boolean false while non-null pointers are converted into true. From the C++11 standard, section on Boolean Conversions:

算术、无作用域枚举、指针或指向成员类型的指针的纯右值可以转换为类型的纯右值布尔.零值、空指针值或空成员指针值被转换为;任何其他值都转换为.类型的纯右值std::nullptr_t可以转换为纯右值类型bool;结果值是.

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 . A prvalue of type std::nullptr_t can be converted to a prvalue of type bool ; the resulting value is false .

这篇关于我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6