LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 10

Moving from a const object falls back to copying Answer, explanation & discussion

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

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

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

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

D get_const() { const D d; return d; }

int main() {
    const D c;
    D a = std::move(c);
    D b = static_cast<const D&&>(D());
    std::cout << '\n';
    return 0;
}
  • A copy copy Correct
  • B move move
  • C copy move
  • D move copy
Correct Answer: Option A

Both arguments are const rvalues (const D&&), which cannot bind to D(D&&) but can bind to D(const D&). (get_const is not called.)

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