Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 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 tofalse; any other value is converted totrue. A prvalue of typestd::nullptr_tcan be converted to a prvalue of typebool; the resulting value isfalse.
这篇关于我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
