hello~ 很高兴见到大家! 这次带来的是C++中关于智能指针这部分的一些知识点,如果对你有所帮助的话,可否留下你宝贵的三连呢? 个 人 主 页: 默|笙

一个智能指针类的基本结构:
template<class T>
class SmartPtr
{
public:
SmartPtr(T* ptr)
:_ptr(ptr)
{
}
~SmartPtr()
{
cout << "delete:" << _ptr << endl;
delete[] _ptr;
}
// 重载运算符,模拟指针的行为,方便访问资源
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
T& operator[](size_t i)
{
return _ptr[i];
}
public:
T* _ptr;
};C++标准库中的智能指针都在头文件<memory>里,只要包了这个头文件就能够使用接下来的几种智能指针。 其中出了weak_ptr智能指针外,其他的都是应用了RAII的设计思路。
struct Date
{
int _year;
int _month;
int _day;
Date(int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{}
~Date()
{
cout << "~Date()" << endl;
}
};
int main()
{
auto_ptr<Date> ap1(new Date);
auto_ptr<Date> ap2(ap1);
return 0;
}拷贝之前:

拷贝之后,可以看到,ap1被置空了,它的管理的资源都转移到了ap2那里。


unique_ptr<Date> up1(new Date);//用指向资源的指针进行构造
unique_ptr<Date> up2(up1);//不支持拷贝
unique_ptr<Date> up3 = make_unique<Date>();//支持make_unique,移动构造
unique_ptr<Date> up4(Date());//易错点,这里编译器会识别成函数声明,这样调用不了移动构造
up1 = up2;//不支持赋值
shared_ptr<Date> sp1(new Date);//用指向资源的指针进行构造
shared_ptr<Date> sp2 = sp1;//拷贝构造
shared_ptr<Date> sp3 = make_shared<Date>(Date());//利用make_shared函数模板默认构造sp3
shared_ptr<Date> sp1(new Date[10], DeleteArray<Date>());
shared_ptr<Date> sp2(new Date[10], [](Date* ptr) {delete[] ptr; });
unique_ptr<Date, DeleteArray<Date>> up1(new Date[5]);
template<class T>
class shared_ptr
{
public:
shared_ptr(T* ptr = nullptr)
:_ptr(ptr)
, _pcount(new int(1))
{ }
template<class D>
shared_ptr(T* ptr, D del)
: _ptr(ptr)
, _pcount(new int(1))
, _del(del)
{ }
shared_ptr(const shared_ptr<T>& sp)
:_ptr(sp._ptr)
,_pcount(sp._pcount)
,_del(sp._del)
{
++(*_pcount);
}
shared_ptr<T>& operator=(const shared_ptr<T>& sp)
{
if (this != &sp)
{
release();
_ptr = sp._ptr;
_pcount = sp._pcount;
++(*_pcount);
_del = sp._del;
}
return *this;
}
void release()
{
if (--(*_pcount) == 0)
{
_del(_ptr);
delete _pcount;
}
}
~shared_ptr()
{
release();
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
T& operator[](int i)
{
return *(_ptr + i);
}
T* get()const
{
return _ptr;
}
int use_count()const
{
return *_pcount;
}
private:
T* _ptr;
int* _pcount;
std::function<void(T*)> _del = [](T* ptr) {delete ptr; };
};
std::shared_ptr\<ListNode> n1(new ListNode);
std::shared_ptr\<ListNode> n2(new ListNode);
n1->next = n2;
n2->prev = n1;
今天的分享就到此结束啦,如果对读者朋友们有所帮助的话,可否留下宝贵的三连呢~~ 让我们共同努力, 一起走下去!