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'?
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.
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() .
You could use the de-reference operator: SomeClass sc = *val; Alternatively, you can use the get() method: SomeClass sc = val.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With