Does it make sense to use std::forward to a universal reference which is not passed further ahead to a function?

Viewed 62

i am a bit confused on the usage of std::forward with a specific use-case. Let's assume the following:

template <typename Store, typename... Args>
auto get(Store&& store, Args&&... args)
{
    return store.get(std::forward<Args>(args)...) // 1
    return std::forward<Store>(store).get(std::forward<Args>(args)...) // 2
}

Which of the //1 or //2 return statements is correct? Does it depend on the get method? (Main concern is if i have to forward the store even though i am not passing it further ahead in the call chain).

1 Answers

If store is an rvalue reference, then your caller is implicotly making the promise that you are free to consume its state.

When you forward, you conditionally make the same promise to the member function get. Is that promise appropiate here? I think it is.

In practice, an rvalue overloaded get could sensibly and efficiently extract some data from the object, or skip some bookkeeping cleanup, in producing its return value.

An example of this technique is the value method on std optional.

Related