Sidd Sidd - 8 days ago 7
C++ Question

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 }

Answer

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)