LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 5

Reusing a moved-from string by assigning to it Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 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>
#include <vector>

int main() {
    std::vector<std::string> lines;
    std::string buf = "first line that is long enough";
    lines.push_back(std::move(buf));
    buf = "second";                  // assigning to a moved-from object is always fine
    lines.push_back(std::move(buf));
    buf.clear();
    buf += "third";
    lines.push_back(buf);
    std::cout << lines.size() << ' ' << lines[1] << ' ' << lines[2] << ' ' << buf << '\n';
    return 0;
}
  • A 3 second third third Correct
  • B 3 second third
  • C 3 third third
  • D 2 second third
Correct Answer: Option A

A moved-from string can be given a new value. The last push_back copies (buf is an lvalue), so buf keeps "third".

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