Sam Shen Sam Shen - 1 year ago 75
C++ Question

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


be a shared/unique pointer. Are
if (p)
if (p.get())

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

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download