LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 12

std::swap performs three moves Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

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

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

struct S {
    int v;
    explicit S(int x) : v(x) {}
    S(S&& o) noexcept : v(o.v) { std::cout << "mc "; }
    S& operator=(S&& o) noexcept { v = o.v; std::cout << "ma "; return *this; }
};

int main() {
    S a(1), b(2);
    std::swap(a, b);
    std::cout << "| " << a.v << b.v << '\n';
    return 0;
}
  • A mc ma ma | 21 Correct
  • B ma ma ma | 21
  • C mc mc mc | 21
  • D | 21
Correct Answer: Option A

The generic std::swap does: T tmp = move(a); a = move(b); b = move(tmp); – one move construction and two move assignments.

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