Search code examples
c++c++14forwarding-reference

Forwarding reference for return type


Is there a difference between those those two

struct S;
int& foo(S&);

auto&& bar1(S& s) {
    return foo(s);
}

decltype(auto) bar2(S& s) {
    return foo(s);
}

for the compiler? I've been always using decltype(auto) in cases like this but is seems auto&& does the trick. Is it a coincidence or are both the identical?


Solution

  • For your particular case it results in the same: The deduced return type of both bar1() and bar2() is int&.

    However, note that auto&& always results in a reference, i.e., bar1() is always going to return by reference regardless of whether foo() returns by value or by reference. On the other hand, declaring bar2() return's type as decltype(auto) will result in bar2() returning by value if foo(s) returns by value (which is not your case).

    I guess you want to perfectly forward the object returned by foo(s). If so, that is actually decltype(auto)'s use case. Think of it: if foo() had returned by value, then bar1()'s return type would have been deduced to int&, i.e., returning a reference to a temporary.