LearnFrenzy
Sign in Take a free test

Move Semantics · Predict the Output · Question 18

Moving a class whose member is a unique_ptr Answer, explanation & discussion

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

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

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

struct Image {
    std::string name;
    std::unique_ptr<int[]> pixels;
    Image(std::string n, int size) : name(std::move(n)), pixels(std::make_unique<int[]>(size)) {}
};

int main() {
    Image a("logo", 100);
    a.pixels[0] = 255;
    Image b = std::move(a);
    std::cout << b.name << ' ' << b.pixels[0] << ' ' << (a.pixels == nullptr) << ' ' << a.name.size() << '\n';
    return 0;
}
  • A logo 255 1 0 Correct
  • B logo 255 0 4
  • C logo 0 1 0
  • D Compilation error
Correct Answer: Option A

The implicit move constructor moves each member: the unique_ptr becomes null and the string (in practice) empty.

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