Check for null in std::shared_ptr

Solution 1:

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).

Solution 2:

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.

Solution 3:

There's no general answer to this question. You have to treat it just like any other pointer. If you don't know whether it's null, test. If you believe it to never be null, assert() that it's not null and use it directly.

The fact that you have a reference to shared_ptr, or even that you have a shared_ptr, has no impact here.

Solution 4:

There is no point in passing a shared_ptr as reference.

You can obtain the internal object via boost::shared_ptr<T>.get() and check for nullptr

Also relevant: move to std :)

Edit: This is the implementation: http://www.boost.org/doc/libs/1_55_0/boost/smart_ptr/shared_ptr.hpp And here is a SO thread about ref or no ref: Should I pass a shared_ptr by reference?

It uses move semantics when Cx11 and copies two ints otherwise which is slower than passing a reference but when is somebody on this level of optimization?