Sobes.tech
Junior — Middle

How to implement a smart pointer std::shared_ptr in C++?

sobes.tech AI

Answer from AI

std::shared_ptr is a smart pointer in C++ that implements reference counting to manage the lifetime of an object. The main idea is to store the object on the heap and keep a counter of how many shared_ptrs point to this object. When the last shared_ptr is destroyed or reassigned, the object is automatically deleted.

Working principle:

  1. When creating a shared_ptr, memory is allocated for the object and the reference counter (usually in a control block).
  2. Each time a shared_ptr is copied, the counter increases.
  3. When a shared_ptr is destroyed, the counter decreases.
  4. When the counter reaches zero, the object's destructor is called and the memory is freed.

Example of a simplified implementation:

#include <iostream>

template<typename T>
class SharedPtr {
    T* ptr;
    size_t* ref_count;

public:
    explicit SharedPtr(T* p = nullptr) : ptr(p), ref_count(new size_t(1)) {}

    SharedPtr(const SharedPtr& other) : ptr(other.ptr), ref_count(other.ref_count) {
        ++(*ref_count);
    }

    SharedPtr& operator=(const SharedPtr& other) {
        if (this != &other) {
            release();
            ptr = other.ptr;
            ref_count = other.ref_count;
            ++(*ref_count);
        }
        return *this;
    }

    ~SharedPtr() {
        release();
    }

    T& operator*() { return *ptr; }
    T* operator->() { return ptr; }

private:
    void release() {
        if (--(*ref_count) == 0) {
            delete ptr;
            delete ref_count;
        }
    }
};

int main() {
    SharedPtr<int> sp1(new int(10));
    {
        SharedPtr<int> sp2 = sp1;
        std::cout << *sp2 << std::endl; // 10
    } // sp2 is destroyed, counter decreases
    std::cout << *sp1 << std::endl; // 10
    return 0;
}

This is a simplified example; in a real implementation, additional details are considered (thread safety, casts, weak pointers, etc.).