C++
Beginner
1 min read
weak_ptr: Breaking Cycles and Observing Ownership
Example
#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\n";
}
~Parent() { std::cout << "Parent '" << name << "' destroyed\n"; }
};
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\n";
}
~Child() { std::cout << "Child '" << name << "' destroyed\n"; }
void greetParent() const {
if (auto p = parent.lock()) { // lock() returns shared_ptr or empty
std::cout << name << " greets parent: " << p->name << "\n";
} else {
std::cout << name << ": parent is gone\n";
}
}
};
// 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() << "\n";
}
};
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;
}
Related Resources
This is the last lesson in this section.
Create a free account to earn a certificate