Search code examples
c++c++11shared-ptrsmart-pointers

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


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 }

Solution

  • 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)