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.

View Repository


Class Descriptions

CRefCounter Class

  • Role:
    • A base class for objects that need reference counting.
  • Key Methods:

CSharedPtr<T> Class

  • Role:
    • A smart pointer that manages the lifetime of a dynamically allocated resource using reference counting.
  • Key Methods:

Code Breakdown

Usage Example

int 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;
}
Example demonstrating the use of CSharedPtr with reference counting to manage the memory of a CObject.