Search code examples
c++shared-ptr

Check for null in std::shared_ptr


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();  
    ...  
}

Solution

  • Most shared pointers are exactly like normal pointers in this respect. You have to check for null. Depending on the function, you may want to switch to using

    void myFunction( Foo const& foo );
    

    , and calling it by dereferencing the pointer (which pushes the responsibility for ensuring that the pointer is not null to the caller).

    Also, it's probably bad practice to make the function take a shared pointer unless there are some special ownership semantics involved. If the function is just going to use the pointer for the duration of the function, neither changing it or taking ownership, a raw pointer is probably more appropriate, since it imposes less constraints on the caller. (But this really depends a lot on what the function does, and why you are using shared pointers. And of course, the fact that you've passed a non-const reference to the shared pointer supposes that you are going to modify it, so passing a shared pointer might be appropriate.)

    Finally, different implementations of shared pointers make it more or less difficult to check for null. With C++11, you can use std::shared_ptr, and just compare it to nullptr naturally, as you'd expect. The Boost implementation is a bit broken in this respect, however; you cannot just compare it to 0 or NULL. You must either construct an empty boost::shared_ptr for the comparison, or call get on it and compare the resulting raw pointer to 0 or NULL.