Summary - Smart pointers
- C++ course
- Intermediate
- Lesson 87/116
- 5 min
Combine unique_ptr, shared_ptr and RAII to write a resource pool.
Summary - Smart pointers
In this group you learned std::unique_ptr, std::shared_ptr, std::weak_ptr, make_unique/make_shared and the RAII pattern. Now we combine them to write a resource pool.
First we will create an exclusive-owner resource with std::make_unique. Then we will add a shared resource with std::make_shared and print the owner count with use_count. This shows how smart pointers work together in a real scenario.
Practice Create a resource with unique_ptr
Create an exclusive-owner resource with auto p = std::make_unique<int>(100);. Print the value *p with std::cout.
Starter code
#include <iostream>
#include <memory>
int main() {
// Create a resource with value 100 via make_unique, print
return 0;
}Sample solution
#include <iostream>
#include <memory>
int main() {
auto p = std::make_unique<int>(100);
std::cout << *p;
return 0;
}Expected output
100
Practice Add a shared_ptr and count
Take the previous step's make_unique call. Add a newline with std::cout << *p << "\n";. Then create a shared resource with auto sp = std::make_shared<int>(200);. Print *sp and sp.use_count() separated by a space.
Starter code
#include <iostream>
#include <memory>
int main() {
auto p = std::make_unique<int>(100);
std::cout << *p;
// Add a shared_ptr, print value and use_count
return 0;
}Sample solution
#include <iostream>
#include <memory>
int main() {
auto p = std::make_unique<int>(100);
std::cout << *p << "\n";
auto sp = std::make_shared<int>(200);
std::cout << *sp << " " << sp.use_count();
return 0;
}Expected output
100 200 1
Smart pointers recap
Smart pointers are the foundation of memory management in modern C++. std::unique_ptr provides exclusive ownership, std::shared_ptr shared ownership, std::weak_ptr weak observation. make_unique and make_shared are safe creation functions.
The RAII pattern is the foundation of resource management: the constructor acquires, the destructor releases. Thanks to this pattern resources are safely released even on exception. You have now completed the intermediate C++ topics; at the advanced level you will study concurrency, metaprogramming and performance optimization.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which smart pointer is for exclusive ownership?
// single owner, cannot be copied- std::unique_ptr Correct answer
- std::shared_ptr
- std::weak_ptr
- std::auto_ptr
Explanation: unique_ptr provides exclusive ownership.
2 Complete the make_unique call
auto p = std::____<int>(100);
auto p = std::make_unique<int>(100);
Explanation: make_unique safely creates a unique_ptr.