Programs & Examples
Smart Pointers · Study material
A file-system tree owned with unique_ptr
Each node owns its children through unique_ptr, while the parent link is a plain pointer (an observer). Destroying the root frees the entire tree with no explicit delete.
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// Children are owned with unique_ptr; the parent link is a plain observer pointer
struct Node {
std::string name;
Node* parent = nullptr;
std::vector<std::unique_ptr<Node>> children;
explicit Node(std::string n) : name(std::move(n)) {}
Node* add(std::string n) {
children.push_back(std::make_unique<Node>(std::move(n)));
children.back()->parent = this;
return children.back().get();
}
std::string path() const { return parent ? parent->path() + "/" + name : name; }
int count() const { int c = 1; for (const auto& ch : children) c += ch->count(); return c; }
};
int main() {
Node root("home");
Node* asha = root.add("asha");
Node* docs = asha->add("docs");
docs->add("cv.pdf");
asha->add("music");
root.add("ravi")->add("notes.txt");
std::cout << docs->children[0]->path() << '\n' << root.count() << " nodes\n";
return 0; // destroying root frees the whole tree automatically
}
home/asha/docs/cv.pdf 7 nodes
Breaking a team–employee cycle with weak_ptr
The cycle example shows how one weak link lets both objects be freed when the last outside owner goes away.
Keeping a session alive in a callback
The enable_shared_from_this example extends an object's lifetime until a pending callback has run.