LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 7

std::forward versus std::move in a template Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links