Question 7
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <string>
#include <utility>
void take(const std::string&) { std::cout << "L "; }
void take(std::string&&) { std::cout << "R "; }
template <typename T> void fwd(T&& x) { take(std::forward<T>(x)); }
template <typename T> void mov(T&& x) { take(std::move(x)); }
int main() {
std::string s = "hi";
fwd(s); fwd(std::string("t"));
mov(s); mov(std::string("t"));
std::cout << '\n';
return 0;
}
- A L R R R Correct
- B L R L R
- C R R R R
- D L L L L
Correct Answer: Option A
std::forward keeps s an lvalue; std::move turns everything into an rvalue – including the caller's s, which take(std::string&&) could then steal from.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!