Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }
like image 262
Sidd Avatar asked Nov 29 '16 00:11

Sidd


People also ask

How do I check if a pointer is null pointer?

int * pInt = NULL; To check for a null pointer before accessing any pointer variable.

Can a Shared_ptr be null?

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 .

Can a pointer be null?

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.

How do you check if something is null in C++?

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.


1 Answers

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)
like image 149
πάντα ῥεῖ Avatar answered Sep 29 '22 07:09

πάντα ῥεῖ