std::optional specialization for reference types

后端 未结 5 2110
时光取名叫无心
时光取名叫无心 2020-12-06 09:34

Why std::optional (std::experimental::optional in libc++ at the moment) does not have specialization for reference types (compared

5条回答
  •  情深已故
    2020-12-06 09:59

    There is indeed something that has reference to maybe existing object semantics. It is called a (const) pointer. A plain old non-owning pointer. There are three differences between references and pointers:

    1. Pointers can be null, references can not. This is exactly the difference you want to circumvent with std::optional.
    2. Pointers can be redirected to point to something else. Make it const, and that difference disappears as well.
    3. References need not be dereferenced by -> or *. This is pure syntactic sugar and possible because of 1. And the pointer syntax (dereferencing and convertible to bool) is exactly what std::optional provides for accessing the value and testing its presence.

    Update: optional is a container for values. Like other containers (vector, for example) it is not designed to contain references. If you want an optional reference, use a pointer, or if you indeed need an interface with a similar syntax to std::optional, create a small (and trivial) wrapper for pointers.

    Update2: As for the question why there is no such specialization: because the committee simply did opt it out. The rationale might be found somewhere in the papers. It possibly is because they considered pointers to be sufficient.

提交回复
热议问题