Return Forwarded Link

I want to create a maximum function that sends a larger value to the result while preserving the type of the link (rvalue or lvalue).

#include <utility>

template<typename T>
constexpr T&& mmax(T&& left, T&& right) {
    return left > right ? std::forward<T>(left) : std::forward<T>(right);
}

int main() {
    mmax(1, 2);
}

However it gives me

max.cc: In instantiation of 'constexpr T&& mmax(T&&, T&&) [with T = int]':
max.cc:9:14:   required from here
max.cc:5:72: warning: returning reference to temporary [-Wreturn-local-addr]
     return left > right ? std::forward<T>(left) : std::forward<T>(right);

Why? I am using GCC 4.8.2 with -std = C ++ 11.

Change . This does not happen with clang ++.

+3
source share
1 answer

Your source code should work because of the rules about the conditional statement in C ++ 11 5.16 / 4:

If the second and third operands are glvalues ​​of the same category of values ​​and have the same type, the result of this type and category of values

forward<T>(left) forward<T>(right) lvalues, x, glvalues, T, , .

, (, , ):

return std::forward<T>(left > right ? left : right);
+3

All Articles