LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 15

A member function overloaded on & and && Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 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>

class Builder {
    std::string s_;
public:
    Builder& add(const std::string& x) & { s_ += x; return *this; }
    std::string build() const & { std::cout << "[copy] "; return s_; }      // object stays usable
    std::string build() && { std::cout << "[steal] "; return std::move(s_); } // object is a temporary
};

int main() {
    Builder b;
    b.add("ab").add("cd");
    std::string x = b.build();
    std::string y = std::move(b).build();
    std::cout << x << ' ' << y << '\n';
    return 0;
}
  • A [copy] [steal] abcd abcd Correct
  • B [copy] [copy] abcd abcd
  • C [steal] [steal] abcd
  • D [copy] [steal] abcd
Correct Answer: Option A

Ref-qualifiers choose an overload by the object's value category: an lvalue builder copies its string, an rvalue builder gives it away.

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