Search code examples
c++boostboost-optional

boost::optional<T&> vs T*


I'm trying to understand when is the right time to use some of the structures that come with boost and had a question regarding the use of boost::optional with a reference.

Suppose I have the following class, using boost::optional:

class MyClass {
public:
   MyClass() {}

   initialise(Helper& helper) {
      this->helper = helper;
   }

   boost::optional<Helper&> getHelper() {
      return helper;
   }

private:
   boost::optional<Helper&> helper;
}

Why would I use the above instead of:

class MyClass {
public:
   MyClass() : helper(nullptr) {}

   initialise(Helper& helper) {
      this->helper = &helper;
   }

   Helper* getHelper() {
      return helper;
   }

private:
   Helper* helper;
}

They both convey the same intent, i.e. that getHelper could return null, and the caller still needs to test if a helper was returned.

Should you only be using boost::optional if you need to know the difference between 'a value', nullptr and 'not a value'?


Solution

  • Compared to a raw pointer, an optional reference may suggest that (1) pointer arithmetic is not used, and (2) ownership of the referent is maintained elsewhere (so delete will clearly not be used with the variable).