LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 2

Copy assignment versus move assignment Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

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

main.cpp
#include <iostream>
#include <utility>

struct A {
    A() = default;
    A& operator=(const A&) { std::cout << "copy= "; return *this; }
    A& operator=(A&&) noexcept { std::cout << "move= "; return *this; }
};

int main() {
    A x, y;
    x = y;
    x = A();
    x = std::move(y);
    std::cout << '\n';
    return 0;
}
  • A copy= move= move= Correct
  • B copy= copy= move=
  • C copy= move= copy=
  • D move= move= move=
Correct Answer: Option A

y is an lvalue (copy); A() is a prvalue and std::move(y) an xvalue – both rvalues, so move assignment.

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