Ask Your Question
0

Can you create your own shared pointer class in C++?

asked 2023-05-20 01:55:07 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-20 02:23:01 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-20 01:55:07 +0000

Seen: 14 times

Last updated: May 20 '23