我有一个函数,它返回一个指向给定名称的 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/