C++ Intermediate · Lesson 03 of 27
Smart pointers: std::shared_ptr and std::weak_ptr
Shared ownership, reference counts, weak observers and breaking cycles.
Estimated time · 60–90 min
Learning goals
What you will understand
- Explain smart pointers: std::shared_ptr and std::weak_ptr in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
std::shared_ptr<T> lets several owners share an object; it is deleted when the last owner is gone (a reference count). std::weak_ptr observes without owning, and lock() gives a shared_ptr if the object is still alive. Create shared pointers with std::make_shared.
ROS 2 hands you shared pointers everywhere: nodes, messages and publishers. Use weak_ptr for back-references such as a child pointing to its parent; two shared_ptrs pointing at each other form a cycle and never free.
Guided lesson
Work through these steps
- 1.
Read the smart pointers: std::shared_ptr and std::weak_ptr example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
#include <memory>
// Header for the smart pointers.
struct Status { int fault{0}; };
// Shared status data.
auto status = std::make_shared<Status>();
// Create a shared object; the count is 1.
auto viewer = status;
// Copying a shared_ptr adds an owner; the count is 2.
std::cout << status.use_count() << '\n';
// Print the number of owners (2).
std::weak_ptr<Status> watcher = status;
// A weak observer: does not change the count.
status.reset(); viewer.reset();
// Both owners let go, so the Status is destroyed.
if (auto alive = watcher.lock()) {
// lock() returns a shared_ptr only if the object still exists.
std::cout << alive->fault << '\n';
// Not reached here: the object is gone.
} else { std::cout << "expired\n"; }
// The weak_ptr correctly reports that it expired.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Smart pointers: std::shared_ptr and std::weak_ptr. Expected result: 2 expired
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
#include <memory>
struct Status {
int fault{0};
};
int main() {
auto status = std::make_shared<Status>();
// TODO: make viewer a second owner, print use_count(), then create a weak_ptr and reset both owners
if (auto alive = watcher.lock()) std::cout << alive->fault << '\n';
else std::cout << "expired\n";
return 0;
}Expected output
2
expiredStuck? Show the full solution (try it yourself first)
#include <iostream>
#include <memory>
struct Status {
int fault{0};
};
int main() {
auto status = std::make_shared<Status>();
auto viewer = status;
std::cout << status.use_count() << '\n';
std::weak_ptr<Status> watcher = status;
status.reset();
viewer.reset();
if (auto alive = watcher.lock()) std::cout << alive->fault << '\n';
else std::cout << "expired\n";
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Build a Parent that owns Children with shared_ptr where each Child holds a weak_ptr back to the Parent. Log destructors and confirm everything is freed. Then change the back-pointer to shared_ptr and observe the leak.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.