0

In C++, if you have a pointer type and want to do a nullptr check to make sure that the pointer is valid, is it safe to include other checks in the same if statement that include the pointer that is being checked?

For example:

Control* c = nullptr;
if (c && c->is_view())
{
    // do stuff
}

The pointer c is being checked to see if it is nullptr, but in the same conditional statement the is_view() function is being called on the c pointer. The call to is_view() assumes that the pointer is valid.

Is this code safe?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
comp1201
  • 407
  • 3
  • 13
  • `&&` can be overloaded, but it doesnt matter here. It might if the expression was `foo && c && c->is_view()` – 463035818_is_not_an_ai Mar 20 '23 at 18:05
  • fwiw, "valid pointer" != "not a nullptr". You can use smart pointers if you want to be able to check if a pointer is valid or not. – 463035818_is_not_an_ai Mar 20 '23 at 18:07
  • @463035818_is_not_a_number `operator&&` can be overloaded only for custom class/struct types, not for built-in types, including pointers. Also, smart pointers merely manage the lifetime of an object, you can't use a smart pointer to just "check if a pointer is valid". It is possible for a smart pointer to hold an invalid pointer, if you are not careful with it. – Remy Lebeau Mar 20 '23 at 18:14
  • 1
    A null pointer is not a valid pointer. But on the flipside, a non-null pointer is not **necessarily** a valid pointer, because it could be a dangling pointer, or a "valid pointer that cannot be dereferenced because it does not point to a valid object, because it is *one-past*" (which has a small set of use cases), or a wild pointer, or an uninitialized pointer. (It was pointed out to me, correctly, that my terminology here is *jargon*, and not **normative**.) – Eljay Mar 20 '23 at 18:14
  • @RemyLebeau what I said. It does not matter for this specific case, but with `custom_foo && c && c->is_view` it might matter. – 463035818_is_not_an_ai Mar 20 '23 at 18:15

0 Answers0