c++ - 我可以将 nullptr 存储到 bool 中吗?

标签 c++ pointers syntax shortcut nullptr

我有一个函数,它返回一个指向给定名称的 bool 类型对象的指针。如果未找到该对象,则返回 nullptr

现在我想将一个变量设置为返回的 bool 值或 false 如果没有找到。我可以这样写吗?

bool flag = *Get("name");

这是否等同于这个更长的实现?

bool *result = Get("name");
bool flag = result == nullptr ? false : *result;

最佳答案

第一个不正确,因为您不能取消引用空指针。

第二个是正确的,但简化为:

bool flag = result && *result;

如果你想避免每次调用的 result 变量,那么这样做:

bool istrue(bool const *result) {
    return result && *result;
}

bool flag = istrue(Get("name"));

关于c++ - 我可以将 nullptr 存储到 bool 中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22066018/

相关文章:

CSS 语法差异

java - Java 矩阵的异常

c++ - string::compare 多余的参数?

c++ - 将绝对地址转换为指针变量的现代 C++ 方法是什么?

c++ - 海湾合作委员会 : Specifying static/dynamic libraries to build against

c - 将字符串数组从 C 返回到 Fortran

c - 设置结构的指针成员,从指针到结构的指针

c++ - 当参数转换为目标类型时,复制构造函数省略以直接初始化

c - 指向 C 中结构表的指针

mysql - 选择语法 - 是 "something = (' this' or 'that' or 'other' )"ok to do?