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)
Related videos on Youtube
Author by
Sidd
Human. Also, a web developer, and designer. Linux enthusiast. Python lover. Married to C++.
Updated on March 26, 2022Comments
-
Sidd about 2 years
I'm trying to check if a
std::shared_ptr
is null. Is there a difference between doingstd::shared_ptr<int> p; if (!p) { // method 1 } if (p == nullptr) { // method 2 }
-
Richard Hodges over 7 yearsNo difference at all. You could also write if(not p.get())
-
πάντα ῥεῖ over 7 yearsWhat about
if (p.get() == nullptr)
? -
Galik over 7 yearsNo difference. One is a lot less typing.
-
-
Yakk - Adam Nevraumont over 7 yearsIn 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 theT*
, 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 about 2 yearsI do not agree with your intent being explicit in your example. The intent is to check for
nullptr
, sop != nullptr
is more explicit for the question. In your example you are only explicit about your intent to invokeoperator bool
. -
Antonio about 2 years@SergeyKolesnik The intent is about knowing if the shared_ptr has been set/reset