How to use boost::optional

A default-constructed boost::optional is empty – it does not contain a value, so you can’t call get() on it. You have to initialise it with a valid value:

boost::optional<myClass> value = myClass();

Alternatively, you can use an in-place factory to avoid copy initialisation (but the copy will most likely be elided anyway); however, I have no experience with that, so I can’t provide an example.


As a side note, you can use -> in place of get(), like this:

value->setInt(10);

But that’s just a matter of stylistic preference, both are equally valid.

Leave a Comment