Hacker News new | past | comments | ask | show | jobs | submit login

operator*() and operator->() on an empty std::optional is Undefined Behavior. This is mind-boggling. It defeats the whole purpose of using a wrapper type to enforce bulletproof error checking. It's the worst of both worlds: you have to use a cumbersome type, and it still fails like a nullable pointer.



yes, it is a somewhat baffling feature. the only practical use I can imagine for it is to avoid calling the copy constructor with an invalid instance of the type and/or to avoid a heap allocation. otherwise, it would be much more natural (and no less safe) for a c++ programmer to just use some flavor of pointer. in the case of pair<bool,T>, one would expect an optimizing compiler to skip the constructor call for an invalid instance anyway if the object was only accessed after checking the bool (unless the constructor has side-effects, yikes!).


I think most of this is just because C++ doesn't have very good pattern matching and didn't want to introduce new operators. (FWIW, using operator*() and operator->() feel very natural, although they are unsafe without using operator bool() as you have mentioned.)




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: