Smart Pointers in C++
Manage memory automatically in C++ with unique_ptr and shared_ptr. See ownership move, reference counting with use_count, and when each object dies.
1#include <iostream>2#include <memory>3using namespace std;45class MyClass {6private:7 int value;89public:10 MyClass(int v) : value(v) {11 cout << "MyClass object created with value: " << value << endl;12 }1314 void display() {15 cout << "Value: " << value << endl;16 }1718 ~MyClass() {19 cout << "MyClass object destroyed (value: " << value << ")" << endl;20 }21};2223int main() {24 cout << "=== unique_ptr ===" << endl;25 {26 // unique_ptr - exclusive ownership27 unique_ptr<MyClass> ptr1 = make_unique<MyClass>(10);28 ptr1->display();2930 // Cannot copy, but can move31 unique_ptr<MyClass> ptr2 = move(ptr1);32 if (ptr1 == nullptr) {33 cout << "ptr1 is now null (ownership transferred)" << endl;34 }35 ptr2->display();36 } // Automatically deleted3738 cout << "\n=== shared_ptr ===" << endl;39 {40 // shared_ptr - shared ownership41 shared_ptr<MyClass> ptr1 = make_shared<MyClass>(20);42 cout << "Reference count: " << ptr1.use_count() << endl;4344 {45 shared_ptr<MyClass> ptr2 = ptr1; // Share ownership46 cout << "Reference count: " << ptr1.use_count() << endl;47 ptr2->display();48 } // ptr2 goes out of scope4950 cout << "Reference count: " << ptr1.use_count() << endl;51 ptr1->display();52 } // Automatically deleted when count reaches 05354 cout << "\nAll objects automatically destroyed" << endl;5556 return 0;57}
Sample Output
ptr1 is now null (ownership transferred)
After move(ptr1).
Reference count: 2
ptr1 and ptr2 share ownership.
MyClass object destroyed (value: 20)
The last shared_ptr went away.
In this one
- How unique_ptr gives single, movable ownership
- Why unique_ptr cannot be copied
- How shared_ptr counts owners with use_count
- When objects are destroyed and why weak_ptr exists
How it works
- 1
make_unique creates value 10; ptr1 owns it.
- 2
move(ptr1) transfers ownership to ptr2; ptr1 becomes null.
- 3
Leaving the block destroys the object.
- 4
make_shared creates value 20 with count 1; copying raises it to 2.
- 5
Counts drop back as owners leave; the object dies at 0.
Edge cases
Copying a unique_ptr
Write unique_ptr<MyClass> p2 = ptr1;
It does not compile, because unique_ptr's copy constructor is deleted. Use move to transfer ownership.
Using a moved-from unique_ptr
Call ptr1->display() after move.
ptr1 is null, so this is a null dereference and undefined behavior.
What's going on
Smart pointers are classes that hold a pointer and delete it for you. They put RAII into the standard library, so you rarely need a bare delete in modern C++. This program shows the two main ones.
unique_ptr means one owner. make_unique<MyClass>(10) creates the object (and needs C++14). ptr1->display() works like a normal pointer. You cannot copy a unique_ptr, because two owners would both try to delete. You can move it: unique_ptr<MyClass> ptr2 = move(ptr1); hands ownership to ptr2 and leaves ptr1 empty, which the null check confirms. At the closing brace, ptr2 is destroyed and deletes the object, printing "MyClass object destroyed (value: 10)".
shared_ptr means shared ownership with a reference count, which is the number of shared_ptrs currently owning the object. make_shared<MyClass>(20) starts the count at 1. Copying it into ptr2 raises the count to 2. When the inner block ends, ptr2 is destroyed and the count drops back to 1. Only when the last owner, ptr1, goes away does the count reach 0 and the object get deleted.
Which to use: unique_ptr by default. It costs nothing extra over a raw pointer. Use shared_ptr only when several parts of the program truly need to keep the same object alive.
One trap with shared_ptr: if two objects hold shared_ptrs to each other, the counts never reach 0 and both leak. weak_ptr breaks such cycles by watching without owning.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <memory> is there because it provides smart pointer classes (unique_ptr, shared_ptr). Leave one out and the compiler stops at the first name it does not recognize.
Understanding Smart Pointers
Smart Pointer Concept:
Types:
unique_ptr - Exclusive Ownership
Basic Usage:
unique_ptr<int> ptr = make_unique<int>(10);
What happens here:
Automatic Cleanup:
{
unique_ptr<int> ptr = make_unique<int>(10);
// Use ptr
} // ptr automatically deleted here
shared_ptr - Shared Ownership
Basic Usage:
shared_ptr<int> ptr1 = make_shared<int>(10);
shared_ptr<int> ptr2 = ptr1; // Share ownership
What happens here:
Reference Counting:
When to Use Smart Pointers
Good fits:
Example Scenarios:
Advantages Over Raw Pointers
Automatic Cleanup:
Memory Safety:
Modern C++:
Important Considerations
unique_ptr:
shared_ptr:
Performance:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does ptr1.use_count() print right after shared_ptr<MyClass> ptr2 = ptr1;?
Pick an answer to check it.
Question 2
Why can a unique_ptr be moved but not copied?
Pick an answer to check it.
Questions people ask
Does unique_ptr have overhead?
Practically none compared with a raw pointer.
Why make_shared instead of shared_ptr(new T)?
It does one allocation for the object and the count together, and is exception-safe.
What is weak_ptr?
A non-owning observer of a shared_ptr object, used to break reference cycles.