隐式将null指针强制转换为bool [英] Implicit cast of null pointer to bool

查看:138
本文介绍了隐式将null指针强制转换为bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有Foo* foo = nullptr;

如果我正在检查foo是否为nullptr,我可以写吗

If I'm checking whether or not foo is nullptr, am I permitted to write

if (!foo)

或者我应该写

if (foo == nullptr)

推荐答案

请参阅此标准参考(加粗强调):

See this standard reference (bold emphasis mine):

C ++ 11§4.12布尔转换

算术,无作用域枚举,指针或指向的指针的prvalue 成员类型可以转换为bool类型的prvalue. 零值, 空指针值,或将空成员指针值转换为 错误的;任何其他值都将转换为true.类型的prvalue std :: nullptr_t可以转换为bool类型的prvalue;这 结果值为假.

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.

中间一句很重要:它告诉您可以将空指针值(foo = nullptr) 隐式转换为本身具有bool类型的false.因此if (!foo)是定义明确的.

The middle sentence is relevant: it is telling you that the null pointer value (foo = nullptr) can be implicitly cast to false which itself has type bool. Therefore if (!foo) is well-defined.

这篇关于隐式将null指针强制转换为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆