ProgrammingHardMicrosoft/Amazon SDE MCQ · GATE CS

What is printed?

What is printed?
int main() {
    auto a = make_shared<int>(1);
    auto b = a;
    { auto c = b; cout << a.use_count(); }
    weak_ptr<int> w = a;
    cout << a.use_count();
    b.reset();
    cout << w.use_count();
}
  1. A. 332
  2. B. 331
  3. C. 321
  4. D. 322

Correct answer: C. 321

Inside the block a, b and c share ownership (3). After it c is gone (2), and a weak_ptr does not add to use_count. b.reset() leaves a as the only owner, so w.use_count() is 1.

More OOP with C++ and Java questions

Exams that ask this topic