Does it make sense to combine optional with reference_wrapper?

前端 未结 2 1631
庸人自扰
庸人自扰 2021-02-05 04:09

It occurred to me that in C++ it is possible to use the type std::optional>. An object of this type is essentially a reference

2条回答
  •  我寻月下人不归
    2021-02-05 04:51

    Is there any conceptual difference between std::optional> and T*?

    std::optional<>, as the name already suggest, is meant to be used when we could have a value or might not have any value at all.

    The equivalent of having no value for a T* object would be assigning nullptr to it, i.e.: the pointer will point to nowhere, as opposed to somewhere (or even anywhere, i.e.: uninitialized). It can be said that std::optional<> exports the concept of nullptr for pointers to any arbitrary type. So, I would say they are conceptually very similar, being the std::option<> approach a kind of generalization.

    Is there any practical difference? Are there situations where it might be advisable to choose std::optional> over T*?

    I can think of the size. std::optional<> contains an internal flag for indicating the presence/absence of a value, whereas for T* the nullptr is encoded directly as one of the values the pointer can store. So a std::optional> object will be larger than a T*.

    When it comes to safety, unlike T*, std::optional<> provides the member function value() which throws an exception if there is no value (it provides as well as the unsafe operator*() as T* does).

    Also, using std::optional> instead of T* , for example, as a function's return value may indicate in a more explicit way that there might be no value at all.

提交回复
热议问题