Shared_ptr 参考实现

简介

为了防止我们忘记对一个指针对象的释放, C++11出现了shared_ptr. 我们也可以手动实现一个shared_ptr.

参考

https://blog.csdn.net/yanchenzhi/article/details/107591037

code

主要需要实现 类模板
实现空构造函数, 指向对象的构造函数.
赋值构造函数

函数重载 * =
妙处在 重载 = 的时候, 我们判断了一下如果就是本身直接返回, 如果不是本身, 自己的count和ptr_需要判断一下是否需要析构.

template <typename T>
class Shared_mptr{
private:
    int *count; // 计数用
    T* ptr_; // 真正指向的对象
public:
    Shared_mptr():count(nullptr), ptr_(nullptr){}
    Shared_mptr(T *p): count(new int(1)), ptr_(p){} // 赋值构造函数
    Shared_mptr(Shared_mptr<T> &other):count(&(++*other.count)), ptr_(other.ptr_){} // 拷贝构造函数
    T* operator->() {return ptr_;} // 这个说实话没有用到, 我暂时也不知道怎么用orz
    T& operator*() { return *ptr_; } // T operator*() { return *ptr_; } 这样也可以
    Shared_mptr<T> & operator=(Shared_mptr<T>& other) { // 重载 = 
        if(this == &other) {
            return *this;
        }
        ++*other.count;
        if(this->ptr_ && --*this->count == 0) {
            delete ptr_;
            delete count;
            cout << "delete from =" << endl;
        }
        this->count = other.count;
        this->ptr_ = other.ptr_;
        return *this;
    }
    ~Shared_mptr() {
        if(this->ptr_ && --*this->count == 0) {
            delete ptr_;
            delete count;
            cout << "delete from ~" << endl;
        }
    }
    int getRef() {
        return *count;
    }
};


int main() {
    Shared_mptr<int> pstr(new int(2));
    cout << "pstr: " << pstr.getRef() << " " << *pstr << endl;

    Shared_mptr<int> pstr2(pstr);
    cout << "pstr: " << pstr.getRef() << " " << *pstr << endl;
    cout << "pstr2: " << pstr2.getRef() << " " << *pstr2 << endl;

    Shared_mptr<int> pstr3(new int(4));
    cout << "pstr3: " << pstr3.getRef() << " " << *pstr3 <<endl;

    pstr3 = pstr2;
    cout << "pstr:" << pstr.getRef() << " " << *pstr << endl;
    cout << "pstr2: " << pstr2.getRef() << " " << *pstr2 << endl;
    cout << "pstr3: " << pstr3.getRef() << " " << *pstr3 << endl;
    Shared_mptr<int>* pstr4 = &pstr;
    int *p = new int(3);
    int a = 4;
    cout << (*p) << " " << sizeof(p) << " " << sizeof(a) << " " << sizeof(*p)<< endl;
    //cout << pstr4->getRef() << " "  << endl;
    return 0;
}
上一篇:linux中container_of


下一篇:智能指针4-----》weak_ptr