'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 1:[1]
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)
Solution 2:[2]
shared_ptr provides a specific operator for bool conversion std::shared_ptr::operator bool.
Test if not set:
if (!p)
Test if set:
if (p)
You can be very explicit about your intent with:
if (static_cast<bool>(p))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | πάντα ῥεῖ |
| Solution 2 | Antonio |
