LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 9

Copying a shared_ptr versus copying the object Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 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 a = std::make_shared<int>(1);
    auto b = a;                               // same object
    auto c = std::make_shared<int>(*a);       // new object with the same value
    *b = 50;
    *c += 1;
    std::cout << *a << ' ' << *b << ' ' << *c << ' ' << (a == b) << (a == c) << '\n';
    return 0;
}
  • A 50 50 2 10 Correct
  • B 1 50 2 10
  • C 50 50 51 11
  • D 50 50 2 11
Correct Answer: Option A

b shares a's object; c owns a separate copy. shared_ptr == compares the stored pointers, not the values.

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