Is there a place for anti-std::move in C++

82 Views Asked by At

boost::optional can store references, so suppose I want to write a function like this

T frob(const boost::optional<const T&> x) {
    return x.value_or(T{42});
}

This fails on a static_assert that the argument passed to value_or for reference holding optionals should not be an rvalue reference. I see that authors of boost library decided to safeguard me against something like

auto& l = x.value_or(T{42});

where I could get a dangling reference to a temporary.

But if "I know what I'm doing" I could circumvent this with something like

T frob(const boost::optional<const T&> x) {
    return x.value_or(to_lvalue(T{42}));
}

where to_lvalue could be defined like

template<class T>
T& to_lvalue(T&& r) {
    return r;
}

Can an argument be made that this is a good "I know what I'm doing" usecase for such a function or am I missing something bigger here?

0

There are 0 best solutions below