Question 15
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#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!