实现shared_ptr类

实现shared_ptr类 需要 定义两个私有变量:指向对象的指针 T* ptr,计数指针int *count;

需要实现一个初始构造函数,拷贝构造函数,析构函数,重载操作符*,-> = 。

 

实现代码如下:

template <typename T>
class sharedPtr
{
public:
    sharedPtr(T* ptr)
    {
        count = new int(1);
        this->ptr = ptr;
    }
    sharedPtr(sharedPtr<T> &other)
    {
        ++(*other->count);
        count = other->count;
        ptr = other->ptr;
    }
    T* operator->()
    {
        return ptr;
    }
    T& operator*()
    {
        return *ptr;
    }
    sharedPtr<T>& operator=(sharedPtr<T>& other)
    {
        ++(*other->count);
        if(ptr && 0 == --(*count))
        {
            delete count;
            delete ptr;
        }
        count = other->count;
        ptr = other->ptr;
        return *this;
    }
    ~sharedPtr()
    {
        if(0 == --(*count))
        {
            delete count;
            delete ptr;
        }
    }
private:
    int* count;
    T* ptr;
};

 

上一篇:C++实现简易共享指针


下一篇:条款19:使用`std::shared_ptr`管理具备共享所有权的资源