什么是共享指针
共享智能指针是指多个智能指针可以同时管理同一块有效的内存,共享智能指针 shared_ptr 是一个模板类。
共享指针,允许多个指针指向同一对象,它是一种计数指针。当引用计数变为0时,会将所指向的对象析构。
作用:用于实现自动内存回收
本质是一个对象
共享指针的基础使用
#include <iostream>
#include <memory>
using namespace std;
int main()
{
// 使用智能指针管理一块 int 型的堆内存
shared_ptr<int> ptr1(new int(520));
cout << "ptr1管理的内存引用计数: " << ptr1.use_count() << endl;
// 使用智能指针管理一块字符数组对应的堆内存
shared_ptr<char> ptr2(new char[12]);
cout << "ptr2管理的内存引用计数: " << ptr2.use_count() << endl;
// 创建智能指针对象, 不管理任何内存
shared_ptr<int> ptr3;
cout << "ptr3管理的内存引用计数: " << ptr3.use_count() << endl;
// 创建智能指针对象, 初始化为空
shared_ptr<int> ptr4(NULL);
cout << "ptr4管理的内存引用计数: " << ptr4.use_count() << endl;
return 0;
}
一个简易共享指针的设计
#include <iostream>
using namespace std;
class Count /*计数器类*/
{
public:
Count() /*构造函数*/
{
count = 1;
}
void add() /*计数器加1*/
{
++count;
}
void sub() /*计数器减1*/
{
--count;
}
int get() const /*获取当前计数值*/
{
return count;
}
private:
int count;
};
template <typename T>
class Shareptr
{
public:
Shareptr(); /*默认构造*/
Shareptr(T *ptr); /*有参构造*/
Shareptr(const Shareptr &obj); /*拷贝构造(浅拷贝)*/
~Shareptr(); /*析构函数*/
Shareptr &operator=(const Shareptr &obj); /*赋值函数重载*/
T *operator->() const; /*指向运算符重载*/
T *operator*() const; /*指针运算符重载*/
T *get(); /*获取对象地址*/
int use_count(); /*对对象计数*/
private:
T *my_ptr; /*指针*/
Count *ptr_count; /*指针记录*/
void clear(); /*释放指针空间和指针记录空间*/
};
template <typename T>
void Shareptr<T>::clear()
{
if (ptr_count)
{
ptr_count->sub();
if (ptr_count->get() == 0)
{
if (my_ptr)
{
delete my_ptr;
}
delete ptr_count;
}
}
}
template <typename T>
Shareptr<T>::Shareptr(T *ptr)
{
my_ptr = ptr;
ptr_count = new Count;
}
template <typename T>
Shareptr<T>::Shareptr()
{
my_ptr = NULL;
ptr_count = new Count;
}
template <typename T>
Shareptr<T>::Shareptr(const Shareptr &obj)
{
this->my_ptr = obj.my_ptr;
this->ptr_count = obj.ptr_count;
ptr_count->add();
}
template <typename T>
Shareptr<T>::~Shareptr()
{
clear();
}
template <typename T>
Shareptr<T> &Shareptr<T>::operator=(const Shareptr<T> &obj)
{
clear();
this->my_ptr = obj.my_ptr;
this->ptr_count = obj.ptr_count;
obj.ptr_count->add();
return *this;
}
template <typename T>
T *Shareptr<T>::operator->() const
{
return *my_ptr;
}
template <typename T>
T *Shareptr<T>::operator*() const
{
return *my_ptr;
}
template <typename T>
T *Shareptr<T>::get()
{
return my_ptr;
}
template <typename T>
int Shareptr<T>::use_count()
{
return ptr_count->get();
}
int main()
{
Shareptr<int> myptr1(new int);
cout << "myptr1:" << myptr1.get() << endl;
{
cout << myptr1.use_count() << endl;
Shareptr<int> myptr2 = myptr1;/*调用拷贝构造函数*/
cout << "myptr2:" << myptr2.get() << endl;
cout << myptr1.use_count() << endl;
cout << myptr2.use_count() << endl;
Shareptr<int> myptr3;
myptr3 = myptr1;/*调用赋值函数*/
cout << "myptr3:" << myptr3.get() << endl;
cout << myptr1.use_count() << endl;
cout << myptr3.use_count() << endl;
}
cout << myptr1.use_count() << endl;
return 0;
}
代码效果
以上是本人对于共享指针shared_ptr一点理解,如有错误,请多指正。