C++ memory shared_ptr Class
Example
Create two shared_ptr variables that point to the same int:
shared_ptr<int> ptr1 = make_shared<int>(10);
shared_ptr<int> ptr2 = ptr1;
cout << *ptr2 << "\n";
cout << ptr1.use_count();
Definition and Usage
A shared_ptr is a smart pointer that can have many owners. Unlike a unique_ptr, it can be copied, and all the copies point to the same memory.
C++ keeps count of how many shared_ptr variables point to the memory. The memory is freed when the last one goes out of scope.
The shared_ptr class is defined in the <memory> header file.
Tip: Use make_shared to create a shared_ptr. See make_shared().
Syntax
shared_ptr<type> name = make_shared<type>(value);
type is the data type of the value, like int or string.
Parameter Values
| Parameter | Description |
|---|---|
| value | Optional. The start value of the new memory. |
Technical Details
| Returns: | A shared_ptr object that points to the memory. |
|---|
Related Pages
Read more about smart pointers in our Smart Pointers Tutorial.