Returning lvalue reference to modified rvalue argument

Viewed 51

Is the following valid C++ code? Also why could it possibly be a bad practice? And what is your suggestion for refactoring taking into account that T can be a heavy type?

template<class T>
T& increment(T&& val)
{
    ++val;
    return val;
}

template<class T>
T incremented(T const& val)
{
    return val + 1;
}

int get_int()
{
    return 333;
}

int main()
{   
    auto i0{ get_int() };
    auto const i1{ get_int() };

    increment(i0);
    auto _i1 = incremented(i1);
    auto _i2 = increment(get_int());

    return _i2;
}
0 Answers
Related