danijar
danijar

Reputation: 34185

Can I store nullptr to bool?

I have a function that returns a pointer to an object of type bool for a given name. If the object is not found, nullptr is returned.

Now I would like to set a variable to the value of the returned boolean or false if not found. Can I write it like this?

bool flag = *Get("name");

Is this equivalent to this longer implementation?

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

Upvotes: 0

Views: 548

Answers (5)

utnapistim
utnapistim

Reputation: 27365

The two are not equivalent. The first implementation will cause a segmentation fault (as you will be attempting to dereference a NULL pointer).

The second alternative is correct.

Upvotes: 1

Steve Jessop
Steve Jessop

Reputation: 279305

The first is not correct since you cannot dereference a null pointer.

The second is correct but simplifies to:

bool flag = result && *result;

If you want to avoid the result variable for each call then do it like:

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

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

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234725

If I understand correctly, you want something that can be nullptr, true or false.

The boost libraries (www.boost.org) have an optional class which you could exploit:

boost::optional<bool> foo;

This allows you to check for nullness using if (!foo), and if the converse is true then you use * to recover the boolean value.

Upvotes: 2

filmor
filmor

Reputation: 32232

This is not equivalent. In the first case you are trying to dereference nullptr which will crash while in the second you do a proper check first.

Upvotes: 2

Ashalynd
Ashalynd

Reputation: 12563

No it's not equivalent. In the first case, if your method returns nullptr, you'll probably get runtime error.

Upvotes: 2

Related Questions