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 }
int * pInt = NULL; To check for a null pointer before accessing any pointer variable.
A null shared_ptr does serve the same purpose as a raw null pointer. It might indicate the non-availability of data. However, for the most part, there is no reason for a null shared_ptr to possess a control block or a managed nullptr .
A null pointer has a reserved value that is called a null pointer constant for indicating that the pointer does not point to any valid object or function. You can use null pointers in the following cases: Initialize pointers. Represent conditions such as the end of a list of unknown length.
In C or C++, there is no special method for comparing NULL values. We can use if statements to check whether a variable is null or not.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With