Search code examples
c++c++11shared-ptr

How cautiously should std::shared_ptr be handled?


I was somewhat surprised to find that std::shared_ptr provides no protection (eg, throw an exception) against situations when its pointed-to object has somehow been deleted. I imagine this is for performance reasons; assuming shared_ptr is doing its job the object the shared_ptr points to should have never been deleted, so it'd be silly to waste the cycles constantly checking.

I know I can check explicitly for whether a shared_ptr is valid, but if shared_ptr is "doing its job" to maintain object lifetime it would seem overkill to explicitly check every time I touch a shared_ptr.

So my question is, how cautious should I be in light of this? Is there a "rule of thumb" as to if, how often, or when I should check the shared_ptr?

My best conclusion so far would mimic Java: Any time you're handed a reference to an object in Java that you didn't create, you should check it for null. Would this be a good policy for shared_ptr?


Solution

  • Just like any other pointer, check it before you use it if you have any reason to suspect that it might wrap a null pointer.

    shared_ptr does help to manage the lifetime of an object that it points to, but that is a completely separate task from deciding whether it does point to an object.