0

Is it safe to perform std::move on std::optional<std::vector<int>>?. It's not giving me any compiler or runtime error, but would like to know whether this is valid. This is my sample code snippet.

std::optional<std::vector<int>> from;
// do computation...
auto to = std::move(from);
// do computation...
康桓瑋
  • 33,481
  • 5
  • 40
  • 90
Harry
  • 2,177
  • 1
  • 19
  • 33
  • 2
    Can you share why you are concerned that isn't valid? It would help understand how to best answer your question. – François Andrieux Oct 27 '21 at 14:32
  • @FrançoisAndrieux I don't think `std::optional` has move constructor or move assignment operator taking rvalue references as paramter. – Harry Oct 27 '21 at 14:35
  • 4
    `std::optional` has a perfectly good move constructor, see https://en.cppreference.com/w/cpp/utility/optional/optional, number 3. You'll end up with `to` containing the data of the vector, and `from` containing an empty vector. – Nate Eldredge Oct 27 '21 at 14:37
  • @NateEldredge Thanks for that. I thought its just a normal `struct` with no `move constructor` and `move assignment operator` member functions. – Harry Oct 27 '21 at 14:43
  • 2
    @Harry You don't need to define a custom move constructor or move assignment operator to have move semantics. The compiler generates those for you, as long as you don't do anything to prevent it. See [Are move constructors produced automatically?](https://stackoverflow.com/questions/8283589/are-move-constructors-produced-automatically). "Normal structs" can have move semantics as well. Edit : [Example](https://godbolt.org/z/ha944cf4P). – François Andrieux Oct 27 '21 at 14:47
  • 1
    Since `std::vector` is moveable then `std::optional>` is movable too. Anyway `std::move` doesn't do anything, just do casting of type to make it r-value. So this can't break anything unless later you are using `from`. `auto to = std::move(*from);` is more interesting case. – Marek R Oct 27 '21 at 14:54
  • @MarekR after `std::move`, is `from` still initialized? I mean the `bool` flag inside `std::optional` struct still `true`? – Harry Oct 27 '21 at 15:00
  • 2
    @Harry The link provided by Nate Eldredge contains that information : *"[...] does not make other empty: a moved-from optional still contains a value, but the value itself is moved from."* – François Andrieux Oct 27 '21 at 15:10
  • @Harry optional do not become empty, but vector do: https://godbolt.org/z/GhYbKq6ez – Marek R Oct 27 '21 at 16:13

0 Answers0