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::moveapplied to a value of aconst optionallegal? - Why does the
optional ovstill hold thevector?
Does ov.value() internally create a copy to a temporary which is then moved from?