LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 4

weak_ptr after the last owner disappears Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 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() {
    std::weak_ptr<int> w;
    auto s = std::make_shared<int>(7);
    w = s;
    auto s2 = s;
    std::cout << w.use_count() << w.expired();
    s.reset();
    std::cout << w.use_count() << w.expired();
    s2.reset();
    std::cout << w.use_count() << w.expired() << (w.lock() ? 1 : 0) << '\n';
    return 0;
}
  • A 2010010 Correct
  • B 2011001
  • C 3021010
  • D 2010101
Correct Answer: Option A

weak_ptr::use_count reports the number of shared owners: 2, then 1, then 0 – at which point it is expired and lock() is 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