SharedPtr Library
Overview
This library implements a custom shared pointer as a way to deeply understand the internal structure and behavior of C++ smart pointers. It mimics the reference counting mechanism of std::shared_ptr, with added focus on clarity and minimal overhead. The implementation is header-only and aims to provide safe memory management by automatically deleting resources when no longer needed.
Class Descriptions
CRefCounter Class
- Role:
- A base class for objects that need reference counting.
- Key Methods:
- void IncrementRef():
- Increments the reference count.
- void DecrementRef():
- Decrements the reference count.
- Deletes the resource when the count reaches 0.
- void IncrementRef():
CSharedPtr<T> Class
- Role:
- A smart pointer that manages the lifetime of a dynamically allocated resource using reference counting.
- Key Methods:
- These functions are the only ones directly involved in reference count management and pointer assignment.
- CSharedPtr(T* ptr):
- Constructor that takes a raw pointer and increases its reference count.
- CSharedPtr(const CSharedPtr<T>& other):
- Shallow Copy Constructor that shares the pointer and increases the count.
- ~CSharedPtr():
- Destructor that decreases the count and deletes the object if it reaches 0.
- void operator = (T* ptr):
- Assigns a raw pointer, properly updating the reference count.
- void operator = (const CSharedPtr<T>& other):
- Assigns another smart pointer, sharing the resource and adjusting the count.
- CSharedPtr(T* ptr):
- These functions are the only ones directly involved in reference count management and pointer assignment.
Code Breakdown
Usage Example
Example demonstrating the use ofint main() { // create CObject CObject* obj = new CObject; CSharedPtr<CObject> sharedPtr1 = obj; // refCount: 1 CSharedPtr<CObject> sharedPtr2 = obj; // refCount: 2 sharedPtr1 = nullptr; // refCount: 1 sharedPtr2 = nullptr; // refCount: 0, delete CObject return 0; }
CSharedPtr with reference counting to manage the memory of a CObject.