Check for null in std::shared_ptr

user1400995 picture user1400995 · Mar 6, 2014 · Viewed 82.8k times · Source

I was wondering if i need to check whether sp is null before i use it. Correct me if I am wrong but creating an alias will not increase the ref counter and therefore by entering into the method we are working with a shared pointer which we don't know if the embedded pointer has been reset before.. am I correct by assuming this?

Class::MyFunction(std::shared_ptr<foo> &sp)
{    
    ...  
    sp->do_something();  
    ...  
}

Answer

Shoe picture Shoe · Mar 6, 2014

You have to consider that std::shared_ptr is overall still a pointer (encapsulated in a pointer like class) and that it can indeed be constructed to internally be nullptr. When that happens, expressions like:

ptr->
*ptr

leads to undefined behavior. So, yeah, if you are expecting the pointer to also be nullptr, then you should check for its value with:

ptr != nullptr

or

!ptr

(thanks to its operator bool).