1、RAII
利用对象生命周期来控制程序资源。在对象构造时获取资源,在对象析构时释放资源。
2、智能指针的原理
RAII特性、像指针一样去使用。
T&operator*()
{
return *_ptr;
}
T*operator->()
{
return _ptr;
}
3、问题
多个智能指针指向同一块空间,这块空间会被析构多次。也就是智能指针拷贝有问题。
4、unique_ptr
思想:防拷贝。让拷贝和赋值为私有且只有声明;或者直接delete。
5、shared_ptr
(1)思想:每一块资源都有一个计数器,当它为0时才释放空间。注意线程安全的问题。
template<class T>
class shared_ptr
{
public:
shared_ptr(T*ptr = nullptr):_ptr(ptr),_count(new int(1)),_mtx(new mtx){}
shared_ptr(const shared_ptr<T>& sp):_ptr(sp._ptr),_count(sp._count),_mtx(sp._mtx)
{
AddRef();//这块新的资源的引用+1
}
shared_ptr<T>& operator=(const shared_ptr<T>&sp)
{
if(_ptr!=sp._ptr)
{
Release();//原来的资源count--
_ptr = sp._ptr;
_mtx = sp._mtx;
_count = sp._count;
AddRef();
}
return *this;
}
~shared_ptr()
{
Release();
}
void Release()
{
_mtx->lock();
bool f = false;
if(--(*_count) == 0 && _ptr)
{
f = true;
delete _ptr;
delete _count;
}
_mtx->unlock();
if(f)delete _mtx;
}
void AddRef()
{
_mtx->lock();
++(*_count);
_mtx->unlock();
}
T&operator()
{
return *_ptr;
}
*Toperator->()
{
return _ptr;
}
private:
T* _ptr;
int* _count;
mutex* _mtx;
}
(2)问题:循环引用->内存泄漏
解决方法:weak_ptr
6、weak_ptr
思想:可以用shared_ptr构造,当它们指向资源时不会引起计数。
7、如何用智能指针管理不是new出来的对象
使用删除器。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。