Shared Pointer (shared_ptr
)
A shared pointer is a type of smart pointer in C++ that helps manage memory dynamically allocated objects. The main purpose of a shared pointer is to allow multiple pointers to share ownership of a dynamically allocated object.
A shared pointer is a type of smart pointer in C++ that allows you to have multiple pointers to share ownership of a dynamically allocated object.
Resources: https://en.cppreference.com/w/cpp/memory/shared_ptr
Usage:
How is it implemented?
shared_ptr
maintains a reference count, which keeps track of how many shared pointers point at this memory. Memory is freed when it hits 0.(Asked in many interviews)
So shared pointers have 2 fields:
- Pointer to the object
- Pointer to an integer storing the reference count
shared_ptr
vs.unique_ptr
?
unique_ptr
represents ownership. Differences betweenunique_ptr
andshared_ptr
When you copy construct, these pointers are copied.
Consider the follow example:
Problems with shared_ptr
There are some problems with shared_ptr
s, that you really need to be careful with.
- Susceptible if you use the constructor
q
has no knowledge ofp
’s existence
Cyclical reference issue
- If we have multiple shared ptrs that point at each other, we have the issue that some pointers may never be deleted