I frequently write functions that take arguments by non-const reference, but the downside is that I can't pass r-values.
A colleague of mine showed me this piece of code which supposedly solves the problem:
#include <iostream>
// example function
int f(int& x) {
x += 5;
return x;
}
// is this undefined behaviour?
auto& to_l_value(auto&& x) {
return x;
}
int main () {
auto y = f(to_l_value(5)); // usage example
std::cout << y; // 10
return 0;
}
Is this undefined behaviour because of a dangling reference? (does 5 get destroyed before f is called?)
When does the temporary get destroyed?