LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 2

Moving a unique_ptr between owners 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 <memory>

int main() {
    auto p = std::make_unique<int>(10);
    auto q = std::move(p);
    *q += 5;
    std::unique_ptr<int> r;
    r = std::move(q);
    std::cout << (p ? *p : -1) << ' ' << (q ? *q : -1) << ' ' << (r ? *r : -1) << '\n';
    return 0;
}
  • A -1 -1 15 Correct
  • B 10 15 15
  • C -1 15 15
  • D 15 15 15
Correct Answer: Option A

Ownership moved from p to q and then to r; the moved-from pointers are null.

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