Why does moving std::optional not reset state

前端 未结 4 923
野趣味
野趣味 2020-12-31 00:23

I was rather surprised to learn that the move constructor (and assignment for that matter) of std::optional does not reset the optional moved from, as can be se

4条回答
  •  梦毁少年i
    2020-12-31 00:51

    While it might be reasonable to expect that std::optional behaves similarly to std::unique_ptr which resets state of moved-from object, there are reasons not to demand such behavior. I think one of them is that std::optional of a trivial type should be a trivially copyable type. As such, it cannot have a non-defaulted move constructor and cannot reset its has_value flag.

    Having std::optional for a non-trivial type behave differently from std::optional for a trivial type is a rather bad idea.

提交回复
热议问题