LearnFrenzy
Sign in Take a free test

Smart Pointers · Smart Pointer Programs · Question 6

Org chart with shared_ptr and weak_ptr links in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Build an organisation chart where managers own reports through shared_ptr and each employee refers back to the manager with weak_ptr; print each person's chain of command and confirm all nodes are freed.

Solution
main.cpp
#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Person {
    std::string name;
    std::weak_ptr<Person> manager;
    std::vector<std::shared_ptr<Person>> reports;
    static inline int alive = 0;
    explicit Person(std::string n) : name(std::move(n)) { ++alive; }
    ~Person() { --alive; }
};

std::shared_ptr<Person> hire(const std::shared_ptr<Person>& boss, const std::string& name) {
    auto p = std::make_shared<Person>(name);
    p->manager = boss;
    boss->reports.push_back(p);
    return p;
}

std::string chain(std::shared_ptr<Person> p) {
    std::string s = p->name;
    while (auto m = p->manager.lock()) { s += " -> " + m->name; p = m; }
    return s;
}

int main() {
    {
        auto ceo = std::make_shared<Person>("Meera");
        auto cto = hire(ceo, "Arjun");
        auto dev = hire(cto, "Asha");
        hire(cto, "Ravi");
        hire(ceo, "Zoya");
        std::cout << chain(dev) << '\n' << chain(cto->reports[1]) << '\n';
        std::cout << "alive " << Person::alive << '\n';
    }
    std::cout << "alive " << Person::alive << '\n';
    return 0;
}

Output Verified by compiling and running

Asha -> Arjun -> Meera
Ravi -> Arjun -> Meera
alive 5
alive 0

Ownership flows down (shared_ptr), back-links are weak, so there are no cycles and everything is freed when the CEO pointer goes away.

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