Is there an effective difference between std::move(*optional) and *std::move(optional)? Which one is preferable?
Full example:
#include <optional>
#include <vector>
void foo()
{
std::optional<std::vector<int>> ov = std::vector<int>{};
std::vector<int> v;
v = std::move(*ov);
}
void bar()
{
std::optional<std::vector<int>> ov = std::vector<int>{};
std::vector<int> v;
v = *std::move(ov);
}
CodePudding user response:
They do the same thing.
In v = std::move(*ov);, *ov is a std::vector<int>& so std::move(*ov) gives you a std::vector<int>&& that you are trying to assign to v.
In v = *std::move(ov); ov is a std::optional<std::vector<int>> so std::move(ov) gives you a std::optional<std::vector<int>>&& and calling * on that calls constexpr T&& operator*() && noexcept; so you again have a std::vector<int>&& that you are trying to assign to v
Personally I prefer v = std::move(*ov); as v = *std::move(ov); makes me go: "Hmm, I am dereferencing, do I have an lvalue like most dereferences give or do I really have an rvalue?" and I would rather not have to ask myself that.
