In other words, how does the implementation keeps track of the count?
Is there a map-like object maintained which is accessible by all the shared_ptr
instances whose key is the pointer's address and value is the number of references? If I've to implement a shared_ptr
, this is the first idea that's coming to my mind.
Is there a possibility for a memory leak in case of these reference-counting smart pointers? If so, how can I avoid them?
Reference counting works by counting the number of references to each object. When the reference count drops to zero the object is definitely unreachable and can be recycled.
The shared reference counter counts the number of owners. Copying a std::shared_ptr increases the reference count by one. Destroying a std::shared_ptr decreases the reference count by one. If the reference count becomes zero, the resource will automatically be released.
You have to enable multiple ownership explicitly by using the Rust type Rc<T> , which is an abbreviation for reference counting. The Rc<T> type keeps track of the number of references to a value to determine whether or not the value is still in use.
To implement reference counting in C++, we need to define a class that maintains a reference counter, supports incrementing and decrementing that counter and destroys and deallocates itself when its counter reaches 0.
I've seen two different non-intrusive approaches to this:
If you go here and scroll to the bottom, there is an excellent diagram which explains these methods much more clearly.
Creating a memory leak with reference-counting smart pointers is very easy. Just create any graph-like structure of objects that has a cycle in the graph. The objects in the cycle will prevent each other from being released. This can't be resolved automatically - for example, when you create a double-link list you have to take care of never removing more than one object at a time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With