Search code examples
c++shared-ptr

Is this a good idiom for passing optional/NULL shared_ptr parameters?


I'm new to shared_ptrs and have been struggling with the right way to handle "optional" pointer arguments. That is, how best to pass pointer arguments to a method, any of which might be NULL on any given invocation. Here's a simplified example using raw pointers:

class Obj {
   SomeType *ptrA;
   SomeType *ptrB;
   ...
   void method(SomeType* a, SomeType* b) {
      ptrA = a;
      ptrB = b;
   }
}

Now switch to shared_ptrs:

class Obj {
   shared_ptr<SomeType> ptrA;
   shared_ptr<SomeType> ptrB;

   // Option 1: pointers to shared pointers:

   void method1(shared_ptr<SomeType>* a, shared_ptr<SomeType>* b) {
      if (a) ptrA = *a;
      else   ptrA.reset();
      // repeat for b
   }

   // Option 2: pass empty shared_ptrs as analog for NULL

   void method2(shared_ptr<SomeType> a, shared_ptr<SomeType> b) {
      ptrA = a;
      ptrB = b;
   }
}

method1 takes pointers to shared_ptrs so callers can pass NULL and you can easily declare arguments with a default value of NULL. However, the logic gets a bit messy and using pointers to shared_ptrs just seems wrong.

method2 requires that the caller create temporary empty shared_ptrs for any "NULL" arguments. That's cumbersome and obscure at best.

Is method1 the best way? Is there a better way? Have I completely missed the boat here?


Solution

  • There is nothing wrong with passing a null shared pointer. In fact, a null shared pointer is an actual Null Object, which means that it's designed exactly for those kinds of uses.