LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 18

Reassigning a shared_ptr changes two counts 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>

int main() {
    auto x = std::make_shared<int>(1);
    auto y = std::make_shared<int>(2);
    auto z = x;
    std::cout << x.use_count() << y.use_count() << ' ';
    z = y;                                 // z leaves x's group and joins y's
    std::cout << x.use_count() << y.use_count() << ' ' << *z << '\n';
    return 0;
}
  • A 21 12 2 Correct
  • B 21 21 2
  • C 21 12 1
  • D 11 12 2
Correct Answer: Option A

Assignment releases the old object (x's count drops) and shares the new one (y's count rises).

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