1 | initial version |
Yes, it is possible to create your own shared pointer class in C++. Here is an example implementation using reference counting:
template<typename T>
class SharedPtr {
public:
explicit SharedPtr(T* ptr = nullptr)
: ptr_(ptr), ref_count_(new int(1))
{}
SharedPtr(const SharedPtr<T>& other)
: ptr_(other.ptr_), ref_count_(other.ref_count_)
{
++*ref_count_;
}
SharedPtr<T>& operator=(const SharedPtr<T>& other)
{
if (this != &other) {
release();
ptr_ = other.ptr_;
ref_count_ = other.ref_count_;
++*ref_count_;
}
return *this;
}
~SharedPtr()
{
release();
}
T* get() const { return ptr_; }
T& operator*() const { return *ptr_; }
T* operator->() const { return ptr_; }
private:
void release()
{
if (--*ref_count_ == 0) {
delete ptr_;
delete ref_count_;
}
}
T* ptr_;
int* ref_count_;
};
This implementation uses a reference count to track the number of shared pointers pointing to the same object. When a new shared pointer is created or copied, the reference count is incremented. When a shared pointer is destroyed or assigned to a new object, the reference count is decremented. If the reference count reaches zero, the object is deleted along with the reference count.