std::shared_ptr
- C++ course
- Intermediate
- Lesson 83/116
- 5 min
Learn shared ownership with std::shared_ptr.
std::shared_ptr
std::shared_ptr provides shared ownership of an object. Multiple shared_ptrs can share the same object; each maintains a reference count. When the last owner is destroyed the object is deleted.
Example: auto p1 = std::make_shared<int>(10); creates a shared_ptr. With auto p2 = p1; you copy it; now there are two owners. p1.use_count() gives the owner count (2). When p1 and p2 go out of scope both end; when the reference count reaches 0 the object is deleted. This is very useful in graph and tree structures.
Copy and count
A shared_ptr can be copied; each copy increments the reference count. auto p2 = p1; copies and the count becomes 2. When a shared_ptr goes out of scope the count decreases by one.
The use_count() method gives the current owner count. This is useful for debugging and verification. The key point: the reference count is managed automatically; you do not increment or decrement it manually. When a shared_ptr is assigned to another, the old object's count decreases and the new one's increases. So there is no leak.
Practice Copy a shared_ptr and count
Create a shared_ptr with std::make_shared<int>(10) and assign it to p1. Copy it with auto p2 = p1;. Print the result of p1.use_count() with std::cout.
Starter code
#include <iostream>
#include <memory>
int main() {
// Create a shared_ptr, copy it, print use_count
return 0;
}Sample solution
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> p1 = std::make_shared<int>(10);
std::shared_ptr<int> p2 = p1;
std::cout << p1.use_count();
return 0;
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Declare a shared_ptr
std::____<int> p1 = std::make_shared<int>(10);
std::shared_ptr<int> p1 = std::make_shared<int>(10);
Explanation: shared_ptr provides shared ownership.
2 What does the use_count() method of shared_ptr return?
auto p1 = std::make_shared<int>(10);
auto p2 = p1;
std::cout << p1.use_count();- Owner count Correct answer
- Total memory amount
- Pointer address
- Object size
Explanation: use_count() returns the owner count (2 in this example).
3 Match each feature to its meaning
| Term | Meaning |
|---|---|
std::shared_ptr |
Shared ownership |
std::make_shared |
Safe creation |
use_count() |
Owner count |
auto p2 = p1 |
Copy |