As mentioned by others, instantiating std::optional
with reference type is ill-formed in the c++14 standard. (See N3690 20.6.2.) Thus using std::optional
as a drop-in replacement for a pointer (that points to a single object whose absence is represented by a value of nullptr
) is not viable unless you are willing to copy the object by value, rather than by reference.
However, the specification leaves the door open to adding such functionality in the future. Additionally, section 7.15 of N3672 suggests a workaround using std::reference_wrapper
.
Update: Additionally, @HowardHinnant informs me that inclusion in the standard has been punted out of c++14 altogether.