Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'?

like image 550
Lee Avatar asked Jun 09 '13 08:06

Lee


People also ask

What is boost :: optional?

Boost C++ Libraries Class template optional is a wrapper for representing 'optional' (or 'nullable') objects who may not (yet) contain a valid value. Optional objects offer full value semantics; they are good for passing by value and usage inside STL containers.

How do I know if my boost Optional is empty?

With is_initialized() you can check whether an object of type boost::optional is not empty. Boost. Optional speaks about initialized and uninitialized objects – hence, the name of the member function is_initialized() .

How do I get the value of a boost optional?

You could use the de-reference operator: SomeClass sc = *val; Alternatively, you can use the get() method: SomeClass sc = val.

Is boost in STD C++?

Boost has been used in C++03 for years, so its the natural choice to use boost versions still in C++11 which are now part of std::, in order to be able to interface with C++03.


1 Answers

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

like image 76
John Zwinck Avatar answered Oct 11 '22 10:10

John Zwinck