Why is the following snippet legal C++ code? This is a purely theoretical question - there is no usecase that I have in mind:
#include <optional>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v{1, 2, 3};
const std::optional<std::vector<int>> ov = v;
const auto nv = std::move(ov.value());
for (const auto& x : *ov) { std::cout << x; }
for (const auto& x : nv) { std::cout << x; }
}
This yields 123123
, but I do not understand the reason.
- Why is a
std::move
applied to a value of aconst optional
legal? - Why does the
optional ov
still hold thevector
?
Does ov.value()
internally create a copy to a temporary which is then moved from?
std::move
, I like to follow a policy that the object moved from is in a valid-but-unspecified state (suitable for re-assignment or destruction). In general. In the OP code, sinceov
isconst
, thestd::move
will not result in the object being gutted and left behind with an empty husk. Regardless, I find following the idiom that the (potentially) moved-from object is as-if it were an ex-parrot works well. In general. (There are exceptions, such as moving from astd::unique_ptr
does leave it in a well specified state.) – Mouthfulstd::vector<T>
is also an exception - a moved-from vector is guaranteed to be empty. – Wordbookstd::vector::clear()
the resulting vector would have been useless. – Wordbookstd::vector<T>
it is always an empty state. – Wordbook