LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 17

auto&& binds to lvalues and rvalues Answer, explanation & discussion

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

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

main.cpp
#include <iostream>
#include <string>
#include <type_traits>

std::string make() { return "tmp"; }

int main() {
    std::string s = "x";
    auto&& a = s;          // forwarding reference: becomes std::string&
    auto&& b = make();     // becomes std::string&& (extends the temporary's lifetime)
    a += "y";
    b += "!";
    std::cout << std::is_lvalue_reference_v<decltype(a)> << std::is_rvalue_reference_v<decltype(b)> << ' ' << s << ' ' << b << '\n';
    return 0;
}
  • A 11 xy tmp! Correct
  • B 10 xy tmp!
  • C 11 x tmp!
  • D 01 xy tmp
Correct Answer: Option A

auto&& follows the same collapsing rules as T&&: an lvalue gives an lvalue reference (so a modifies s), a prvalue gives an rvalue reference that keeps the temporary alive.

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