LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 5

A shared_ptr cycle prevents destruction Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <memory>

struct Node {
    char name;
    std::shared_ptr<Node> next;
    explicit Node(char n) : name(n) {}
    ~Node() { std::cout << "~" << name << ' '; }
};

int main() {
    {
        auto a = std::make_shared<Node>('A');
        auto b = std::make_shared<Node>('B');
        a->next = b;
    }
    std::cout << "| ";
    {
        auto c = std::make_shared<Node>('C');
        auto d = std::make_shared<Node>('D');
        c->next = d;
        d->next = c;               // cycle!
        std::cout << c.use_count() << d.use_count() << ' ';
        d->next.reset();           // break it before leaving the scope
    }
    std::cout << '\n';
    return 0;
}
  • A ~A ~B | 22 ~C ~D Correct
  • B ~B ~A | 22 ~D ~C
  • C ~A ~B | 22
  • D ~A ~B | 11 ~C ~D
Correct Answer: Option A

For the chain, a dies first, and destroying A drops B's last owner. In the cycle each node has two owners; breaking the link by hand lets them be freed – otherwise neither destructor would run.

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