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:
std::shared_ptr<B> p = std::make_shared<B>(...);
shared_ptr<C> q = p; // Later
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:
{
// replace ... with args to create a C object
shared_ptr<C> p = make_shared<C>(...);
if (...) {
shared_ptr<C> q = p;
} // destructor for q runs, reference count is 1
...
} // dtor for p runs, ref count is 0, C object is deleted
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
C* cp = new C{...};
shared_ptr<C> p{cp}; // Incorrect
shared_ptr<C> q{cp}; // Double delete
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
class Node {
shared_ptr<Edge> myEdges;
shared_ptr<Node> neighbors;
}