Why does std::optional not have a specialization for reference types?

When n3406 (revision #2 of the proposal) was discussed, some committee members were uncomfortable with optional references. In n3527 (revision #3), the authors decided to make optional references an auxiliary proposal, to increase the chances of getting optional values approved and put into what became C++14. While optional didn’t quite make it into C++14 for … Read more

How to move from std::optional

It is valid to move from optional<T>::value() since it returns a mutable reference and the move does not destroy the object. If the optional instance is not engaged, value() will throw a bad_optional_access exception (§20.6.4.5). You explicitly check whether the option is engaged: if (content) Process(move(*content)); But you don’t use the member value() to access … Read more

How to get around GCC ‘*((void*)& b +4)’ may be used uninitialized in this function warning while using boost::optional

There are two levels of uninitialized analysis in gcc: -Wuninitialized: flags variables that are certainly used uninitialized -Wmaybe-uninitialized: flags variables that are potentially used uninitialized In gcc (*), -Wall turns on both levels even though the latter has spurious warnings because the analysis is imperfect. Spurious warnings are a plague, so the simplest way to … Read more

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 … Read more

std::optional specialization for reference types

When n3406 (revision #2 of the proposal) was discussed, some committee members were uncomfortable with optional references. In n3527 (revision #3), the authors decided to make optional references an auxiliary proposal, to increase the chances of getting optional values approved and put into what became C++14. While optional didn’t quite make it into C++14 for … Read more

How should one use std::optional?

The simplest example I can think of: std::optional<int> try_parse_int(std::string s) { //try to parse an int from the given string, //and return “nothing” if you fail } The same thing might be accomplished with a reference argument instead (as in the following signature), but using std::optional makes the signature and usage nicer. bool try_parse_int(std::string s, … Read more