Reference count
Reference count in c++ helps program to keep track of pointer usage and delete it from memory when it is no longer needed.
You can read different methods to use reference counts on you program using smart pointers in following pages:
You can check how to get count of reference in each of the smart pointer using below code snippet:
Run it here.
The output of this program would look something like this:
Key points in this example:
We define a simple
MyClass
with a constructor and destructor that print messages when they're called.We use
std::make_shared<MyClass>()
to create ashared_ptr
namedptr1
.We use the
use_count()
member function to get the current reference count of the shared pointer.We create another shared pointer
ptr2
that points to the same object asptr1
. This increases the reference count.We create a weak pointer
weak
fromptr1
. This does not increase the reference count.We reset
ptr2
, which decreases the reference count.Finally, we reset
ptr1
. At this point, the object is destroyed because there are no more shared pointers pointing to it.For the last count, we use
weak.expired()
to check if the object still exists, and if it does, we useweak.lock().use_count()
to get the count. If the object no longer exists, we print 0.
It's important to note that while use_count()
is useful for understanding and debugging shared pointer behavior, you shouldn't rely on it for program logic, as its exact behavior can vary between implementations.
Last updated