C++ Programming
Smart Pointers
Master C++ programming from basics to advanced. Learn object-oriented programming, STL, memory management, and build high-performance applications.
On this page
Smart Pointers
Smart pointers are modern C++ (C++11) objects that manage memory automatically, eliminating many common memory management errors. They're essential for writing safe, modern C++ code.
Why Smart Pointers?
Problems with Raw Pointers:
- ❌ Memory leaks (forgetting to delete)
- ❌ Double deletion (deleting twice)
- ❌ Dangling pointers (using deleted memory)
- ❌ Exception safety issues
Smart Pointers Solve:
- ✅ Automatic memory management
- ✅ Exception safety
- ✅ No memory leaks
- ✅ Clear ownership semantics
Types of Smart Pointers
C++ provides three main smart pointer types:
- `unique_ptr`: Exclusive ownership
- `shared_ptr`: Shared ownership
- `weak_ptr`: Non-owning reference
unique_ptr
Exclusive ownership - only one unique_ptr can own an object at a time.
Basic Usage
1#include <memory>
2using namespace std;
3
4// Creating unique_ptr
5unique_ptr<int> ptr1(new int(10));
6unique_ptr<int> ptr2 = make_unique<int>(20); // Preferred (C++14)
7
8// Accessing
9cout << *ptr1 << endl; // Dereference
10cout << ptr1.get() << endl; // Get raw pointer
11
12// Automatic cleanup when out of scope
Key Features
- Exclusive Ownership: Cannot copy, only move
- Automatic Deletion: Deleted when
unique_ptrgoes out of scope - Custom Deleters: Can specify custom cleanup
- Array Support: Can manage arrays
Examples
1// Cannot copy
2unique_ptr<int> ptr1 = make_unique<int>(10);
3// unique_ptr<int> ptr2 = ptr1; // Error! Cannot copy
4
5// Can move
6unique_ptr<int> ptr2 = move(ptr1); // ptr1 is now nullptr
7
8// Custom deleter
9unique_ptr<FILE, decltype(&fclose)> file(fopen("data.txt", "r"), fclose);
10
11// Array
12unique_ptr<int[]> arr = make_unique<int[]>(10);
13arr[0] = 100;
shared_ptr
Shared ownership - multiple shared_ptr objects can own the same resource.
Basic Usage
1#include <memory>
2using namespace std;
3
4// Creating shared_ptr
5shared_ptr<int> ptr1 = make_shared<int>(10); // Preferred
6shared_ptr<int> ptr2 = ptr1; // Both point to same object
7
8// Reference counting
9cout << ptr1.use_count() << endl; // 2 (ptr1 and ptr2)
10
11// Automatic cleanup when last shared_ptr is destroyed
Reference Counting
shared_ptr uses reference counting:
- Count increases when copied
- Count decreases when destroyed or reset
- Object deleted when count reaches 0
1shared_ptr<int> ptr1 = make_shared<int>(10);
2cout << ptr1.use_count() << endl; // 1
3
4{
5 shared_ptr<int> ptr2 = ptr1;
6 cout << ptr1.use_count() << endl; // 2
7} // ptr2 destroyed, count back to 1
8
9ptr1.reset(); // Object deleted (count = 0)
Custom Deleters
1shared_ptr<int> ptr(new int[10], [](int* p) { delete[] p; });
weak_ptr
Non-owning reference - doesn't affect reference count, used to break circular references.
Problem: Circular References
1struct Node {
2 shared_ptr<Node> next;
3 // Circular reference problem!
4};
5
6shared_ptr<Node> node1 = make_shared<Node>();
7shared_ptr<Node> node2 = make_shared<Node>();
8node1->next = node2;
9node2->next = node1; // Circular! Memory leak!
Solution: weak_ptr
1struct Node {
2 weak_ptr<Node> next; // Use weak_ptr
3};
4
5shared_ptr<Node> node1 = make_shared<Node>();
6shared_ptr<Node> node2 = make_shared<Node>();
7node1->next = node2;
8node2->next = node1; // No circular reference!
9
10// Accessing weak_ptr
11if (auto locked = node1->next.lock()) {
12 // Use locked shared_ptr
13}
Comparison Table
| Feature | unique_ptr | shared_ptr | weak_ptr |
|---|---|---|---|
| Ownership | Exclusive | Shared | None |
| Copyable | No | Yes | Yes |
| Movable | Yes | Yes | Yes |
| Reference Count | N/A | Yes | No |
| Overhead | Minimal | Small | Small |
| Use Case | Single owner | Multiple owners | Break cycles |
Best Practices
- ✅ Prefer `make_unique` and `make_shared` over
new - ✅ Use `unique_ptr` by default (simpler, faster)
- ✅ Use `shared_ptr` only when shared ownership is needed
- ✅ Use `weak_ptr` to break circular references
- ✅ Don't mix raw and smart pointers for same object
- ✅ Avoid circular references with
shared_ptr - ✅ Don't create `shared_ptr` from raw pointer multiple times
- ✅ Use `weak_ptr` to check if object still exists
Common Patterns
Pattern 1: Factory Function
1unique_ptr<MyClass> createObject() {
2 return make_unique<MyClass>();
3}
Pattern 2: Polymorphism
1class Base { };
2class Derived : public Base { };
3
4unique_ptr<Base> ptr = make_unique<Derived>();
Pattern 3: Container of Smart Pointers
1vector<unique_ptr<MyClass>> objects;
2objects.push_back(make_unique<MyClass>());
make_unique vs new
Prefer `make_unique`:
1// Good
2auto ptr = make_unique<int>(10);
3
4// Avoid
5unique_ptr<int> ptr(new int(10));
Benefits:
- Exception safe
- More efficient (single allocation for
shared_ptr) - Cleaner syntax
- Type deduction
Custom Deleters
Smart pointers support custom deleters:
1// Function deleter
2void customDelete(int* p) {
3 cout << "Deleting..." << endl;
4 delete p;
5}
6
7unique_ptr<int, decltype(&customDelete)> ptr(new int(10), customDelete);
8
9// Lambda deleter
10unique_ptr<int, function<void(int*)>> ptr2(
11 new int(10),
12 [](int* p) { delete p; }
13);
Sample Output
Deleting...
Common Mistakes
- ❌ Creating multiple
shared_ptrfrom same raw pointer - ❌ Circular references with
shared_ptr - ❌ Using
shared_ptrwhenunique_ptris enough - ❌ Not checking
weak_ptrbefore use - ❌ Mixing raw and smart pointers
- ❌ Returning raw pointer from smart pointer function
Migration from Raw Pointers
Old Style:
1int* ptr = new int(10);
2// ... use ptr ...
3delete ptr; // Easy to forget!
Modern Style:
1auto ptr = make_unique<int>(10);
2// ... use ptr ...
3// Automatically deleted!
Next Module
In Module 13, we'll learn about Exception Handling - how to handle errors gracefully in C++!
Hands-on Examples
unique_ptr Basics
#include <iostream>
#include <memory>
using namespace std;
class Resource {
private:
int id;
public:
Resource(int i) : id(i) {
cout << "Resource " << id << " created" << endl;
}
~Resource() {
cout << "Resource " << id << " destroyed" << endl;
}
void use() {
cout << "Using resource " << id << endl;
}
};
int main() {
cout << "=== Creating unique_ptr ===" << endl;
{
unique_ptr<Resource> ptr1 = make_unique<Resource>(1);
ptr1->use();
// Cannot copy
// unique_ptr<Resource> ptr2 = ptr1; // Error!
// Can move
unique_ptr<Resource> ptr2 = move(ptr1);
if (ptr1 == nullptr) {
cout << "ptr1 is now nullptr" << endl;
}
ptr2->use();
// Automatic cleanup when out of scope
}
cout << "Resources destroyed automatically" << endl;
// Array support
cout << "\n=== Array unique_ptr ===" << endl;
{
unique_ptr<int[]> arr = make_unique<int[]>(5);
for (int i = 0; i < 5; i++) {
arr[i] = i * 10;
}
cout << "Array: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
return 0;
}unique_ptr provides exclusive ownership. Cannot be copied, only moved. Automatically deletes managed object when out of scope. Use make_unique for creation. Supports arrays with unique_ptr<T[]>. Perfect for single-owner scenarios.
Sample Output
=== Creating unique_ptr === Resource 1 created Using resource 1 ptr1 is now nullptr Using resource 1 Resource 1 destroyed Resources destroyed automatically === Array unique_ptr === Array: 0 10 20 30 40
Practice with Programs
Reinforce your learning with hands-on practice programs
Related Program Topics
Recommended Programs
Array Max & Min
BeginnerFind the largest and smallest values in a C++ array in one pass, starting from INT_MIN and INT_MAX. Traces 10 5 20 15 8 and shows why starting at 0 fails.
Array Average
BeginnerCompute the average of n numbers stored in a C++ array, adding them up as they are read. Covers double for the sum, setprecision(2), and the n = 0 trap.
Merge Arrays
BeginnerMerge two integer arrays into one in C++ by copying the first array, then the second after it. Learn the n1 + i offset and how to size the merged array.