Is there a recommended way to test if a smart pointer is null?

18,920

Is there a difference between doing

 std::shared_ptr<int> p;
 if (!p) { // method 1 }
 if (p == nullptr) { // method 2 }

No, there's no difference. Either of that operations has a properly defined overload.

Another equivalent would be

 if(p.get() == nullptr)
Share:
18,920

Related videos on Youtube

Sidd
Author by

Sidd

Human. Also, a web developer, and designer. Linux enthusiast. Python lover. Married to C++.

Updated on March 26, 2022

Comments

  • Sidd
    Sidd about 2 years

    I'm trying to check if a std::shared_ptr is null. Is there a difference between doing

    std::shared_ptr<int> p;
    if (!p) { // method 1 }
    if (p == nullptr) { // method 2 }
    
    • Richard Hodges
      Richard Hodges over 7 years
      No difference at all. You could also write if(not p.get())
    • πάντα ῥεῖ
      πάντα ῥεῖ over 7 years
      What about if (p.get() == nullptr)?
    • Galik
      Galik over 7 years
      No difference. One is a lot less typing.
  • Yakk - Adam Nevraumont
    Yakk - Adam Nevraumont over 7 years
    In theory the 3rd one could be more complex in relatively insane situations, as it must get the T* prior to comparing to nullptr. Imagine a type erased smart pointer that must call a vtable method prior to getting the T*, but if the value is null guarantees a nullptr vtable. Method 1 and 2 can short circuit the possible extract-T*, while 3 could not, because .get() does not know it will be just checked for null.
  • Sergey Kolesnik
    Sergey Kolesnik about 2 years
    I do not agree with your intent being explicit in your example. The intent is to check for nullptr, so p != nullptr is more explicit for the question. In your example you are only explicit about your intent to invoke operator bool.
  • Antonio
    Antonio about 2 years
    @SergeyKolesnik The intent is about knowing if the shared_ptr has been set/reset