Why does moving std::optional not reset state

前端 未结 4 927
野趣味
野趣味 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条回答
  •  死守一世寂寞
    2020-12-31 01:09

    What that paragraph says is that if that optional had a value, it still has a value. Since that value has been moved from (to the newly constructed object), it could be a different value than what it had before the move. This allows you to access the moved-from optional object the same way as a moved-from non-optional object, so the behavior of a T vs. optional (when it contains an object) when accessed after the move is the same.

    Also, the overall effect of a move from an optional depends on how the contained type T handles a move. Other classes (like vector) do not have this dependency.

提交回复
热议问题