LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 3

A user-declared destructor turns moves into copies Answer, explanation & discussion

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

struct Tracked {
    Tracked() = default;
    Tracked(const Tracked&) { std::cout << "copy "; }
    Tracked(Tracked&&) noexcept { std::cout << "move "; }
};

struct Plain  { Tracked t; };
struct Logged { Tracked t; ~Logged() {} };     // only a destructor added

int main() {
    Plain p1;
    Plain p2 = std::move(p1);
    Logged l1;
    Logged l2 = std::move(l1);
    std::cout << '\n';
    return 0;
}
  • A move copy Correct
  • B move move
  • C copy copy
  • D copy move
Correct Answer: Option A

Plain gets an implicit move constructor that moves t. Declaring ~Logged() suppresses the implicit move, so std::move(l1) uses the implicit copy constructor.

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