智能指针是一个类,share_ptr采用引用计数器的方法,允许多个智能指针指向同一个对象,每当多一个指针指向该对象 时,指向该对象的所有智能指针内部的引用计数加1,每当减少一个智能指针指向对象时,引用计数会 减1,当计数为0的时候会自动的释放动态分配的资源。
知识点:
delete m_ptr,m_ptr指向的地址所存目标被删除,该目标所占的堆空间也被删除,但是指针p本身没有被删除;
返回值为引用:share_ptr<T>&、T&,不需要创建无名临时对象,避免构造函数和析构函数的调用,从空间和时间上提高了程序执行的效率;
智能指针适用于各类型参数,所以要用T模板。
#include <iostream>
using namespace std;
template <typename T>
class share_ptr {
public:
//1.构造函数
share_ptr() : m_ptr(nullptr), m_count(new int(1)){}
share_ptr(T* ptr) : m_ptr(ptr), m_count(new int(1)){}
share_ptr(const share_ptr& P) : m_ptr(P.m_ptr), m_count(&(++(*P.m_count))){}
//2.析构函数
~share_ptr() {
if (--(*m_count) == 0) {
delete m_ptr;
delete m_count;
cout << "source delete" << endl;
}
}
//3.获得count计数值
int getCount() {
return *m_count;
}
//4.拷贝赋值重载
share_ptr<T>& operator=(const share_ptr<T>& P) {
if (this == &P) return *this;
if (--(*m_count) == 0) {
delete m_ptr;
delete m_count;
cout << "source delete" << endl;
}
m_ptr = P.m_ptr;
m_count = P.m_count;
(*m_count)++;
return *this;
}
//5.重载*
T& operator*() {
return *m_ptr;
}
//6.重载->
T* operator->() {
return m_ptr;
}
private:
T* m_ptr;
int* m_count;
};
测试代码:
int main() {
share_ptr<int> p1(new int(1));
cout << "p1 count的值:" << p1.getCount() << " p1 m_ptr的值:" << *p1 << endl;
share_ptr<int> p2(p1);
cout << "p1 count的值:" << p1.getCount() << " p1 m_ptr的值:" << *p1 << endl;
cout << "p2 count的值:" << p2.getCount() << " p2 m_ptr的值:" << *p2 << endl;
share_ptr<int> p3(new int(5));
cout << "p3 count的值:" << p3.getCount() << " p3 m_ptr的值:" << *p3 << endl;
p3 = p1;
cout << "p1 count的值:" << p1.getCount() << " p1 m_ptr的值:" << *p1 << endl;
cout << "p2 count的值:" << p2.getCount() << " p2 m_ptr的值:" << *p2 << endl;
return 0;
}
测试结果: