Lesson 7 of 7
Practice & Quiz - Memory Management & Smart Pointers
Test your understanding of stack vs heap, RAII, unique_ptr, shared_ptr, and weak_ptr with a practical exercise and 5 quiz questions.
Practical Exercise - Smart Pointer Ownership Chain
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Plugin {
std::string name;
explicit Plugin(std::string n) : name(std::move(n)) {
std::cout << "Plugin " << name << " loaded\n";
}
~Plugin() { std::cout << "Plugin " << name << " unloaded\n"; }
void run() const { std::cout << name << "::run()\n"; }
};
class PluginManager {
std::vector<std::shared_ptr<Plugin>> plugins_;
public:
std::shared_ptr<Plugin> load(std::string name) {
auto p = std::make_shared<Plugin>(std::move(name));
plugins_.push_back(p); // manager shares ownership
return p; // caller also gets a copy
}
void run_all() const {
for (const auto& p : plugins_) p->run();
}
};
void demonstrate() {
PluginManager mgr;
// Caller gets shared_ptr - shares ownership with manager
auto logger = mgr.load("Logger");
auto auth = mgr.load("Auth");
std::cout << "Logger use_count: " << logger.use_count() << "\n"; // 2
// weak_ptr - observe without owning
std::weak_ptr<Plugin> weak_logger = logger;
logger.reset(); // caller gives up ownership
std::cout << "Logger use_count: " << auth.use_count() << "\n"; // 1 (mgr only)
if (auto locked = weak_logger.lock()) {
std::cout << "Logger still alive via weak\n";
}
mgr.run_all();
// mgr destroyed here → plugins destroyed
}
int main() {
demonstrate();
std::cout << "All plugins cleaned up\n";
return 0;
}Module Quiz
Why should you use `std::make_unique<T>()` instead of `std::unique_ptr<T>(new T(...))`?
Tip
Tip
Practice Practice Quiz Memory Management Smart Pointers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Stack vs Heap, new/delete Bugs, unique_ptr, shared_ptr, weak_ptr & RAII Patterns
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Memory Management Smart Pointers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz Memory Management Smart Pointers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Finished this lesson?