Search code examples
c++c++11shared-ptrsmart-pointersunique-ptr

Smart pointer as condition: are if (p) and if (p.get()) equilavent?


Let p be a shared/unique pointer. Are if (p) and if (p.get()) equivalent?

If not, in what cases can these conditionals, or the code within the conditionals, behave differently?

From cppreference I read that std::shared_ptr::operator bool checks whether get() != nullptr. Is this the exact implementation of operator bool?


Solution

  • The "exact implementation" should not be your concern (it will vary from compiler to compiler, from version to version, and possibly based on the options you provide to the compiler)

    Your concern should be "How will a standards-compliant compiler behave" and the answer is "Yes, if(ptr) should always produce the same results as if(ptr.get())

    From the standard:

    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 .

    And smart pointers count as nullable pointers which have the following requirement:

    An object p of type P can be contextually converted to bool (Clause [conv]). The effect shall be as if p != nullptr had been evaluated in place of p.

    (thanks to T.C. for this quote)