Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#include <iostream> #include <memory> #include <string> #include <vector> struct Child; struct Parent { std::string name; std::vector<std::shared_ptr<Child>> children; explicit Parent(std::string n) : name(std::move(n)) { std::cout << "Parent '" << name << "' created "; } ~Parent() { std::cout << "Parent '" << name << "' destroyed "; } }; struct Child { std::string name; std::weak_ptr<Parent> parent; // weak — no ownership cycle explicit Child(std::string n) : name(std::move(n)) { std::cout << "Child '" << name << "' created "; } ~Child() { std::cout << "Child '" << name << "' destroyed "; } void greetParent() const { if (auto p = parent.lock()) { // lock() returns shared_ptr or empty std::cout << name << " greets parent: " << p->name << " "; } else { std::cout << name << ": parent is gone "; } } }; // enable_shared_from_this example class Timer : public std::enable_shared_from_this<Timer> { public: void scheduleCallback() { // Safe: captures a shared_ptr to self auto self = shared_from_this(); std::cout << "Timer scheduled with use_count=" << self.use_count() << " "; } }; int main() { auto parent = std::make_shared<Parent>("Alice"); auto child = std::make_shared<Child>("Bob"); child->parent = parent; // weak link — no cycle parent->children.push_back(child); child->greetParent(); parent.reset(); // Parent destroyed (no cycle) child->greetParent(); // parent is gone // enable_shared_from_this auto timer = std::make_shared<Timer>(); timer->scheduleCallback(); return 0; }
Result
Open