shared_ptr是c++中的一种常用智能指针,它能够解决C++程序员未及时释放内存空间导致的内存泄露问题。shared_ptr的实现核心是改变其中的引用计数值,下面是我实现的一个简单的shared_ptr,其中主要包括拷贝构造函数、赋值运算符等。
#includeusing namespace std; template class myshared_ptr { public: myshared_ptr(T*value) //:ptr(value), count(new int(1)) { ptr = value; count = new int(1); } myshared_ptr(const myshared_ptr&m) { ptr = m.ptr; count = m.count; (*count)++; } myshared_ptr&operator=(const myshared_ptr&m) { if (this != &m) { ptr = m.ptr; count = m.count; (*count)++; } return *this; } T&operator->() { return this->ptr; } ~myshared_ptr() { (*count)--; if (*(this->count) == 0) { delete ptr; delete count; //ptr = nullptr; //count = nullptr; cout << "释放内存空间" << endl; } } public: T*ptr; int*count; }; void testshared_ptr() { myshared_ptr res(new int(2)); cout << *(res.count) << endl; myshared_ptr res2(res); cout << *(res2.count) << endl; myshared_ptr res3 = res; cout << *(res.count)< 执行上面代码输出如下,可见我们通过赋值运算符、拷贝构造函数都会增加引用计数值。而通过析构函数会减少引用计数值,直到引用计数为0时,释放内存空间。
1 2 3 3 3 2 1 释放内存空间参考博客:shared_ptr的简单实现_haitaobiyao的博客-CSDN博客_shared_ptr实现



