Should I move the value out of an optional or move the whole optional?
Asked Answered
B

1

7

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);
}
Bathhouse answered 2/5, 2022 at 15:8 Comment(1)
Both are functionally equivalent, so I guess it depends on personal style.Lyse
M
10

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.

Morentz answered 2/5, 2022 at 15:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.