Questions / Quant development, C++ ownership & memory

A named rvalue reference is an lvalue expression

Challenge, about 10 minutes. Question D131.

C++17. Which overload code does relay(5) return? The overloads and relay template are shown.

int pick(int&) { return 1; }
int pick(int&&) { return 2; }
template<class T> int relay(T&& x) { return pick(x); }
// In main:
std::cout << relay(5);

Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.

Show the answer and worked solution

Answer: 1 overload code

  1. Although x has an rvalue-reference type in this instantiation, the expression x is an lvalue. Passing it directly therefore selects pick(int&) and returns 1.

Interview shortcut. A named rvalue reference is an lvalue.

In the app this has a follow-up where one thing about the setup changes. Try the follow-up.

More c++ ownership & memory questions