简介
为了防止我们忘记对一个指针对象的释放, 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;
}
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》